Java程序只写最后一行?

时间:2015-01-18 21:50:24

标签: java writer

我的问题是,对于读者,作者只输出文件最后一行的内容,我不知道为什么据我所知,我不小心关闭它或任何错误与此类似。这是我用于作家的代码

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();
    }
}

2 个答案:

答案 0 :(得分:1)

看起来你在循环之外创建了你的Writer,然后在循环中关闭它。你确定它只是你得到的最后一行吗?我的猜测是你只能获得第一行。

看起来这需要在下一个大括号之后移动:

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

你应该切换订单,因为flush()如果流已经关闭则不会做任何事情(尽管close()通常flush()调用{。}}。

答案 1 :(得分:0)

你过早关闭作家。

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();
    }
}