The problem with file overwriting files instead of appending to the end

Ok, I am having trouble writing multiple lines to a text file.

the program starts, but it will not use new lines every time

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

a b c d 

it looks like this:

 d 

who knows how to solve this problem? All imports are imported correctly.

source (it is slightly edited, suppose everything is correctly defined):

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

Be sure to create the FileWriter instance that you add to the end. This can be done using this particular FileWriter constructor , which takes an extra boolean as the second parameter. This boolean tells FileWriter append to the end of the file, rather than overwrite the file.

 BufferedWriter outStream= new BufferedWriter(new FileWriter("encoded.txt", true)); 
+15
source

By default, FileWriter will overwrite the file. What you can do is define the reader as follows:
new FileWriter("encoded.txt", true)
Thus, the file will be added in instead of overwritten .

Hope this helps!

+2
source

I'm not sure what this code should do. It gives an error message if your input line is longer than one character, because you close your file in a loop, and then try to write it again.

I interpret your question as follows: you wonder why only the last result is in the file. In this case, this is due to the fact that you did not create your FileWriter in add mode. Look at the various constructors available for FileWriter, and use the one that allows you to add to the file.

0
source

All Articles