Java create and write to a file

In Java, we can use Files.write to create and write to a file. String content = "…"; Path path = Paths.get("/home/mkyong/test.txt"); // string -> bytes Files.write(path, content.getBytes(StandardCharsets.UTF_8)); The Files.write also accepts an Iterable interface; it means this API can write a List to a file. List<String> list = Arrays.asList("a", "b", "c"); Files.write(path, list); Short History …

Read more

How to append text to a file in Java

This article shows how to use the following Java APIs to append text to the end of a file. Files.write – Append a single line to a file, Java 7. Files.write – Append multiple lines to a file, Java 7, Java 8. Files.writeString – Java 11. FileWriter FileOutputStream FileUtils – Apache Commons IO. In Java, …

Read more

How to write to file in Java – BufferedWriter

In Java, we can use BufferedWriter to write content into a file. // jdk 7 try (FileWriter writer = new FileWriter("app.log"); BufferedWriter bw = new BufferedWriter(writer)) { bw.write(content); } catch (IOException e) { System.err.format("IOException: %s%n", e); } Note If possible, uses Files.write instead, one line, simple and nice. List<String> list = Arrays.asList("Line 1", "Line 2"); …

Read more