Java How to create and write to a file
By:Roy.LiuLast updated:2019-08-11
In Java, we can use Files.write (Since JDK 7) to create and write to a file, one line, simple and nice. See the following examples :
Charset utf8 = StandardCharsets.UTF_8;
List<String> list = Arrays.asList("Line 1", "Line 2");
// If the file doesn't exists, create and write to it
// If the file exists, truncate (remove all content) and write to it
Files.write(Paths.get("app.log"), list, utf8);
// If the file doesn't exists, create and write to it
// If the file exists, append to it
Files.write(Paths.get("app.log"), list, utf8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
// For a single line String
Files.write(Paths.get("app.log"), "Hello World".getBytes());
// Create and write to a file in binary format
byte[] bytes = {1, 2, 3, 4, 5};
Files.write(Paths.get("app.bin"), bytes);
1. Files.write
A complete Java NIO Files.write example.
FileExample.java
package com.mkyong;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
public class FileExample {
public static void main(String[] args) {
Charset utf8 = StandardCharsets.UTF_8;
List<String> list = Arrays.asList("Line 1", "Line 2");
try {
// If the file doesn't exists, create and write to it
// If the file exists, truncate (remove all content) and write to it
Files.write(Paths.get("app.log"), list, utf8);
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
// Read
try {
byte[] content = Files.readAllBytes(Paths.get("app.log"));
System.out.println(new String(content));
// for binary
//System.out.println(Arrays.toString(content));
} catch (IOException e) {
e.printStackTrace();
Output
app.log
Line 1 Line 2
2. BufferedWriter
A complete BufferedWriter example.
BufferedWriterExample.java
package com.mkyong.calculator;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
public class BufferedWriterExample {
public static void main(String[] args) {
Charset utf8 = StandardCharsets.UTF_8;
List<String> list = Arrays.asList("Line 1", "Line 2");
String content = "Hello World";
try (Writer writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream("app.log"), utf8)
)) {
writer.write(content + "\n");
for (String s : list) {
writer.write(s + "\n");
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
Output
app.log
Hello World Line 1 Line 2
For append, pass a true as second argument for FileOutputStream.
try (Writer writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream("app.log", true), utf8)
))
From:一号门
Previous:Java How to read a file

COMMENTS