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();
1String fileData = "yourContent";
2FileOutputStream fos = new FileOutputStream("yourFile.txt");
3fos.write(fileData.getBytes());
4fos.flush();
5fos.close();
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