In this source code example, we show you how to write a text or string to the file.
We use Files.write() method to write a text or string to the given file.
Java Write File Example
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
public class JavaWriteFile {
public static void main(String[] args) throws IOException {
Path myPath = Paths.get("src/resources/sample.txt");
List<String> lines = new ArrayList<>();
lines.add("mango");
lines.add("apple");
lines.add("banana");
lines.add("watermelon");
lines.add("orange");
Files.write(myPath, lines, StandardCharsets.UTF_8,
StandardOpenOption.CREATE);
System.out.println("Data written to a file");
}
}
References
Related Java NIO Files Examples
- Java File Copy Example
- Java Create File Example
- Java Delete File Example
- Java File Size Example
- Java Get File Owner Example
- Java File Move Example
- Java Read File Example
- Java Write File Example
- Java Create Directory Example
- Java Create Multiple Directories Example
- Java List All Subdirectories From a Directory Example
- Java Append to File Example
Comments
Post a Comment