1import java.io.FileWriter; // Import the FileWriter class
2import java.io.IOException; // Import the IOException class to handle errors
3
4public class WriteToFile {
5 public static void main(String[] args) {
6 try {
7 FileWriter myWriter = new FileWriter("filename.txt");
8 myWriter.write("Files in Java might be tricky, but it is fun enough!");
9 myWriter.close();
10 System.out.println("Successfully wrote to the file.");
11 } catch (IOException e) {
12 System.out.println("An error occurred.");
13 e.printStackTrace();
14 }
15 }
16}
1PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
2writer.println("The first line");
3writer.println("The second line");
4writer.close();