Java 程序只写最后一行?

Java program only writing last line?

我的问题是 reader 作者只输出文件最后一行的内容,我不确定为什么据我所知我没有不小心关闭它或任何类似的错误。这是我为作者使用的代码

private static void processhtml(String UserFile) throws FileNotFoundException {
    Scanner s = new Scanner(new BufferedReader(
            new FileReader(UserFile))).useDelimiter("\s*:\s*|\s*\n\s*");

    //splits the file at colons
    int count=0;
    String line="";
    String[] words=new String[40];
    try{
        String fileName="test"+count+".html";
        PrintWriter writer = new PrintWriter(fileName, "UTF-8");
        while (s.hasNext()) {
             line =s.nextLine();
             words = line.split("\s*:\s*");

             for(int i=0;i<words.length;i++){
                 writer.println(words[i]);
             }

             writer.close();
             writer.flush();
        }
    }catch(Exception e){
        e.printStackTrace();
    }
}

您似乎是在循环外创建 Writer,然后在循环内关闭它。你确定这只是你得到的最后一行吗?我猜你只会看到第一行。

这似乎需要在下一个大括号之后移动:

        writer.close();
        writer.flush();

而且您可能应该切换顺序,因为如果流已经关闭,flush() 将不会执行任何操作(尽管通常 close() 无论如何都会调用 flush())。

你关闭你的作者太早了。

private static void processhtml(String UserFile) throws FileNotFoundException {
    Scanner s = new Scanner(new BufferedReader(
            new FileReader(UserFile))).useDelimiter("\s*:\s*|\s*\n\s*");

    //splits the file at colons
    int count=0;
    String line="";
    String[] words=new String[40];
    try{
        String fileName="test"+count+".html";
        PrintWriter writer = new PrintWriter(fileName, "UTF-8");
        while (s.hasNext()) {
            line =s.nextLine();
            words = line.split("\s*:\s*");

            for(int i=0;i<words.length;i++){
                writer.println(words[i]);
            }

            /////////////////////////
            // closing writer within loop on first iteration
            writer.close();
            writer.flush();
        }
    }catch(Exception e){
        e.printStackTrace();
    }
}

应该是:

private static void processhtml(String UserFile) throws FileNotFoundException {
    Scanner s = new Scanner(new BufferedReader(
            new FileReader(UserFile))).useDelimiter("\s*:\s*|\s*\n\s*");

    //splits the file at colons
    int count=0;
    String line="";
    String[] words=new String[40];
    try{
        String fileName="test"+count+".html";
        PrintWriter writer = new PrintWriter(fileName, "UTF-8");
        while (s.hasNext()) {
            line =s.nextLine();
            words = line.split("\s*:\s*");

            for(int i=0;i<words.length;i++){
                writer.println(words[i]);
            }

            writer.flush();
        }
        writer.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}