Trouble with filewriter overwriting files instead

2020-01-25 10:37发布

OK, I'm having some trouble writing multiple lines to a text file.

the program runs, but it won't use new lines each time

when I want it run 4 times, the text file should look like:

a
b
c
d

instead, it looks like:

d

who knows how to fix this problem? all imports are correctly imported.

source(it's been slightly edited, assume everything is properly defined):

import java.io.*;
public class Compiler {
public static void main (String args[]) throws IOException
{
    //there's lots of code here
    BufferedWriter outStream= new BufferedWriter(new FileWriter("output.txt"));
    outStream.newLine();
    outStream.write(output);
    outStream.close();
}

}

3条回答
SAY GOODBYE
2楼-- · 2020-01-25 11:07

Make sure that when you create an instance of a FileWriter, that you are appending to the end of it. This can be done by using this specific FileWriter constructor which takes an additional boolean as a second parameter. This boolean tells the FileWriter to append to the end of the file, rather than overwriting the file.

BufferedWriter outStream= new BufferedWriter(new FileWriter("encoded.txt", true));
查看更多
走好不送
3楼-- · 2020-01-25 11:27

By default FileWriter will overwrite the file. What you might want to do is define the reader in the following manner:
new FileWriter("encoded.txt", true)
This way the file will be appended to instead of being overwritten.

Hope this helps!

查看更多
▲ chillily
4楼-- · 2020-01-25 11:27

I'm not sure what this code is supposed to do. It throws an error if your input string is more than one character long, because you close your FileWriter inside the loop, then try to write to it again.

I'm interpreting your question the following way: you're wondering why only the most recent output is in the file. In that case, it's because you didn't create your FileWriter in append mode. Look at the different constructors available for FileWriter, and use the one that allows you to append to the file.

查看更多
登录 后发表回答