The fact that PrintWriter's method is called append() doesn't mean that it changes mode of the file being opened.
You need to open file in append mode as well:
PrintWriter pw = new PrintWriter(new FileOutputStream(
new File("persons.txt"),
true /* append = true */));
Also note that file will be written in system default encoding. It's not always desired and may cause interoperability problems, you may want to specify file encoding explicitly.
Answer from axtavt on Stack OverflowThe fact that PrintWriter's method is called append() doesn't mean that it changes mode of the file being opened.
You need to open file in append mode as well:
PrintWriter pw = new PrintWriter(new FileOutputStream(
new File("persons.txt"),
true /* append = true */));
Also note that file will be written in system default encoding. It's not always desired and may cause interoperability problems, you may want to specify file encoding explicitly.
PrintWriter pw = new PrintWriter(new FileOutputStream(new File("persons.txt"),true));
The true is the append flag. See documentation.
Videos
Do this in order to create a PrinterWriter working with a FileWriter in append mode:
PrintWriter outFile = new PrintWriter(new FileWriter("planetaryData.txt", true));
From Mkyong's tutorials:
FileWriter, a character stream to write characters to file. By default, it will replace all the existing content with new content, however, when you specified a true (boolean) value as the second argument in FileWriter constructor, it will keep the existing content and append the new content in the end of the file.
You can use something like -
PrintWriter outputFile = new PrintWriter(new FileWriter(file, true));
Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.
Java 7+
For a one-time task, the Files class makes this easy:
try {
Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
Careful: The above approach will throw a NoSuchFileException if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Another approach is to pass both CREATE and APPEND options, which will create the file first if it doesn't already exist:
private void write(final String s) throws IOException {
Files.writeString(
Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
s + System.lineSeparator(),
StandardOpenOption.CREATE, StandardOpenOption.APPEND
);
}
However, if you will be writing to the same file many times, the above snippets must open and close the file on the disk many times, which is a slow operation. In this case, a BufferedWriter is faster:
try(FileWriter fw = new FileWriter("myfile.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println("the text");
//more code
out.println("more text");
//more code
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
Notes:
- The second parameter to the
FileWriterconstructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.) - Using a
BufferedWriteris recommended for an expensive writer (such asFileWriter). - Using a
PrintWritergives you access toprintlnsyntax that you're probably used to fromSystem.out. - But the
BufferedWriterandPrintWriterwrappers are not strictly necessary.
Older Java
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
Exception Handling
If you need robust exception handling for older Java, it gets very verbose:
FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
fw = new FileWriter("myfile.txt", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
finally {
try {
if(out != null)
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(fw != null)
fw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
You can use fileWriter with a flag set to true , for appending.
try
{
String filename= "MyFile.txt";
FileWriter fw = new FileWriter(filename,true); //the true will append the new data
fw.write("add a line\n");//appends the string to the file
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
Once you call PrintWriter out = new PrintWriter(savestr); the file is created if doesn't exist hence first check for file existence then initialize it.
As mentioned in it's Constructor Docmentation as well that says:
If the file exists then it will be truncated to zero size; otherwise, a new file will be created.
Since file is created before calling f.exists() hence it will return true always and รฌf block is never executed at all.
Sample code:
String savestr = "mysave.sav";
File f = new File(savestr);
PrintWriter out = null;
if ( f.exists() && !f.isDirectory() ) {
out = new PrintWriter(new FileOutputStream(new File(savestr), true));
}
else {
out = new PrintWriter(savestr);
}
out.append(mapstring);
out.close();
For better resource handling use Java 7 - The try-with-resources Statement
You can also use BufferedWriter:
System.out.println("Enter text to input: ");
String textToAppend = input.nextLine();
//Set true for append mode
BufferedWriter writer = new BufferedWriter(
new FileWriter("C:\\folder 1\\filename.txt", true));
writer.write(textToAppend);
writer.close();
you have to open the file in append mode, which can be achieved by using the FileWriter(String fileName, boolean append) constructor.
output = new BufferedWriter(new FileWriter(my_file_name, true));
should do the trick
The solution with FileWriter is working, however you have no possibility to specify output encoding then, in which case the default encoding for machine will be used, and this is usually not UTF-8!
So at best use FileOutputStream:
Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file, true), "UTF-8"));