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}
1File myObj = new File("path");
2myObj.createNewFile();
3FileWriter myWriter = new FileWriter("path");
4myWriter.write("text");
5myWriter.close();
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 fw = new FileWriter("C:/path/to/filename.txt");
8 fw.write("this is how u write a string");
9 fw.write(String.valueOf(108)); // cast number to string
10 myWriter.close();
11 } catch (IOException e) {
12 ..
13 }
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();
5
1@Test
2public void givenUsingJava7_whenWritingToFile_thenCorrect()
3 throws IOException {
4 String str = "Hello";
5
6 Path path = Paths.get(fileName);
7 byte[] strToBytes = str.getBytes();
8
9 Files.write(path, strToBytes);
10
11 String read = Files.readAllLines(path).get(0);
12 assertEquals(str, read);
13}
14