Write
Lesson 5 of 11 in Coddy's File Handling in Java course.
To write to a file in Java, we can use the FileWriter class:
try {
FileWriter writer = new FileWriter("data.txt");
writer.write("This the new contect of data.txt file!");
writer.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}The above code writes some text to the "data.txt" file, note that you must handle the IOException exception.
In default, the text overrides any existing text, if you want to append the text to the already existing file content, use this:
FileWriter writer = new FileWriter("data.txt", true);Note the true as the second argument to FileWriter constructor.
Challenge
EasyYou are given the file named "coddy.txt" from before. Append to this file the following text:
This is the end of the file, but only the beginning...In the end, print the new file content.
Try it yourself
import java.io.FileWriter;
import java.io.IOException;
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
class Main {
public static void main(String[] args) {
// Write code here
}
}