简体   繁体   English

不逐行书写

[英]not writing line by line

private static void displaytoFile(int trial, int count) {
        // TODO Auto-generated method stub
        String answer;
         try{
              // Create file 
                  FileWriter fstream = new FileWriter(outputfile);
                  BufferedWriter out = new BufferedWriter(fstream);
                  answer = "Case #"+trial+": "+count;
                  out.write(answer);
                  out.newLine();
              //Close the output stream
                out.close();
              }catch (Exception e){//Catch exception if any
                  System.err.println("Error: " + e.getMessage());
              }


    }

The displaytoFile() method is called in a loop in my project but i am not able to write line by line into the file.It only writes the last line ie the parameters passed during the last iteration.I tested in console and the other code is ok,it displays all but this code snippet seems to have some problem as it seems it overwrites the previous values.How can i get to write to file line by line? displaytoFile()方法在我的项目中被循环调用,但是我无法一行一行地写入文件。它仅写入最后一行,即在上一次迭代过程中传递的参数。我在控制台和其他代码中进行了测试可以,它显示所有内容,但此代码段似乎有问题,因为它似乎覆盖了以前的值。如何才能逐行写入文件?

使用FileWriter(String, boolean)构造函数以附加输入,而不是重写整个文件:

FileWriter fstream = new FileWriter(outputfile, true);
 FileWriter fstream = new FileWriter(outputfile);
 BufferedWriter out = new BufferedWriter(fstream);

 answer = "Case #"+trial+": "+count;
 out.write(answer);
 out.newLine();

 //Close the output stream
 out.close();

has problem. 有问题。 This is because inside each iteration of your loop, you clear the file then write current line into it. 这是因为在循环的每次迭代中,您都清除了文件,然后将当前行写入其中。 you should open the file before the loop and close it after the loop. 您应该在循环之前打开文件,然后在循环之后关闭文件。 Or making sure that you are append to the file, not first clear then write, like what you did now. 或者确保像现在所做的那样先添加到文件,而不是先清除然后再写。

You have to indicate that you want to append to the file 您必须指出要附加到文件中

See method documentation here 在此处查看方法文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM