Java Write File Example

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



Comments