If you just need to do this one time, 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
}
Note : Sometimes 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).
However, if you will be writing to the same file many times, the above has to open and close the file on the disk many times, which is a slow operation. In this case, a buffered writer is better:
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 FileWriter constructor 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 BufferedWriter is recommended for an expensive writer (such as FileWriter).
Using a PrintWriter gives you access to println syntax that you're probably used to from System.out.
But the BufferedWriter and PrintWriter wrappers are not strictly necessary.
In Java 7+
If you just need to do this one time, the Files class makes this easy:
Note : Sometimes 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).However, if you will be writing to the same file many times, the above has to open and close the file on the disk many times, which is a slow operation. In this case, a buffered writer is better:
Notes:
FileWriter
constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.)BufferedWriter
is recommended for an expensive writer (such asFileWriter
).PrintWriter
gives you access toprintln
syntax that you're probably used to fromSystem.out
.BufferedWriter
andPrintWriter
wrappers are not strictly necessary.