Java java.nio.file.Files write() Method
java.nio.file.Files.write() is a static method provided in the Java NIO (New I/O) package for efficiently writing data to a file. It is a file I/O operation utility class introduced in Java 7 Files and compared with the traditional java.io package, it provides a more concise and efficient writing approach.
Method Definition
Files.write() The method has multiple overloaded versions for different writing needs:
Write a 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
lines, Charset cs, OpenOption... options ) throws IOException #### Write an iterable collection of strings (using UTF-8 encoding) public static Path write ( Path path, Iterable lines, OpenOption... options ) throws IOException ### Detailed Parameter Explanation #### Basic Parameters - **path**: The file path to write to, of type `java.nio.file.Path` - **bytes**: The byte array to write - **lines**: The collection of strings to write (one string per line) - **cs**: Character set (Charset), used to specify the text encoding #### OpenOption Options The `OpenOption` 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, failing if it already exists - `StandardOpenOption.WRITE`: Open for writing - `StandardOpenOption.APPEND`: Append writing (does not overwrite existing content) - `StandardOpenOption.TRUNCATE_EXISTING`: If the file already exists, clear it --- ## Usage Examples ### Writing a 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 code 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 ( ) ) ; } } } ### Writing 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 Characteristics ### Advantages 1. **Conciseness**: Compared with the traditional `FileOutputStream` and `BufferedWriter`, the code is more concise 2. **Atomicity**: The write operation is atomic, either fully successful or fully failed 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 ### 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 Limit**: When writing large files, loading all content at once may cause insufficient memory 4. **Encoding Issues**: Pay attention to specifying the correct character set when writing text --- ## Best Practices ### Handling Large Files For large files, it is recommended to use `Files.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 Always handle `IOException` appropriately: ## 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 file" , e ) ; } --- ## Summary The `Files.write()` method is a very practical tool 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, you can consider using the `Files.newOutputStream()` or `Files.newBufferedWriter()` methods. In actual development, you should choose the appropriate writing method based on specific needs, and pay attention to exception handling and resource management to ensure the robustness and reliability of the program. [ Java java.nio.file.Files ](/java/java-nio-file.html)
Java java.nio.file.Files