简体   繁体   中英

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?

使用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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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