Java java.nio.file.Files write() Method

Java File Java java.nio.file.Files


java.nio.file.Files.write()is a static method provided by the Java NIO (New I/O) package for efficiently writing data to files. It is part of the file I/O operation utility class introduced in Java 7Files. Compared to the traditionaljava.iopackage, it provides a more concise and efficient way of writing.

Method Definition

Files.write()The method has multiple overloaded versions for different writing needs:

Write byte array

public static Path write(Path path, byte[] bytes, OpenOption... options) throws IOException

Write an iterable collection of strings

public static Path write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options) throws IOException

Write an iterable collection of strings (using UTF-8 encoding)

public static Path write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options) throws IOException

Parameter Details

Basic parameters

  • path: the file path to write to, of typejava.nio.file.Path
  • bytes: the byte array to write
  • lines: the collection of strings to write (one string per line)
  • cs: the Charset, used to specify the text encoding

OpenOption Options

OpenOptionThe parameter is used to specify how the file is opened. Commonly used options include:

  • StandardOpenOption.CREATE: create the file if it does not exist
  • StandardOpenOption.CREATE_NEW: create a new file, fail if the file already exists
  • StandardOpenOption.WRITE: open for writing
  • StandardOpenOption.APPEND: append (do not overwrite existing content)
  • StandardOpenOption.TRUNCATE_EXISTING: truncate the file if it already exists

Usage Examples

Write Byte Array

Example

import java.nio.file.*;
import java.io.IOException;

public class WriteBytesExample {
    public static void main(String[] args) {
        Path path = Paths.get("example.bin");
        byte[] data = {0x48, 0x65, 0x6C, 0x6C, 0x6F}; // ASCII codes of "Hello"
       
        try {
            Files.write(path, data, StandardOpenOption.CREATE);
            System.out.println(Data written successfully);
        } catch (IOException e) {
            System.err.println(Write failed: + e.getMessage());
        }
    }
}

Write Text Lines

Example

import java.nio.file.*;
import java.io.IOException;
import java.util.Arrays;
import java.nio.charset.StandardCharsets;

public class WriteLinesExample {
    public static void main(String[] args) {
        Path path = Paths.get("example.txt");
        Iterable<String> lines = Arrays.asList(First line, Second line, Third line);
       
        try {
            // Write using UTF-8 encoding
            Files.write(path, lines, StandardCharsets.UTF_8,
                       StandardOpenOption.CREATE, StandardOpenOption.APPEND);
            System.out.println(Text written successfully);
        } catch (IOException e) {
            System.err.println(Write failed: + e.getMessage());
        }
    }
}

Method Features

Advantages

  1. Conciseness: compared to the traditionalFileOutputStreamandBufferedWriter, the code is more concise
  2. Atomicity: the write operation is atomic; it either fully succeeds or fully fails
  3. Automatic Closing: no need to manually close the stream; the method handles it internally
  4. High Performance: the underlying implementation is optimized and performs well

Important Notes

  1. File Permissions: ensure the program has write permission for the target file
  2. File Locking: if the file is locked by another process, the write will fail
  3. Memory Limitations: when writing large files, loading all content at once may cause insufficient memory
  4. Encoding Issues: when writing text, be careful to specify the correct character set

Best Practices

Handling Large Files

For large files, it is recommended to useFiles.newBufferedWriter()combined with buffered writing:

Example

try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
    for (String line : largeCollection) {
        writer.write(line);
        writer.newLine();
    }
} catch (IOException e) {
    // Handle exception
}

Error Handling

AlwaysIOExceptionperform appropriate handling:

Example

try {
    Files.write(path, content, StandardOpenOption.CREATE);
} catch (IOException e) {
    // Log, notify the user, or perform recovery operations
    logger.error(File write failed: + path, e);
    throw new RuntimeException(Unable to write to file, e);
}

Summary

Files.write()The method is a very practical utility in Java NIO, especially suitable for simple file writing scenarios. It simplifies file operation code, improves development efficiency, and maintains good performance. For more complex writing needs, consider usingFiles.newOutputStream()orFiles.newBufferedWriter()method.

In actual development, choose the appropriate writing method according to specific needs, and pay attention to exception handling and resource management to ensure the robustness and reliability of the program.

Java File Java java.nio.file.Files

Other Extensions