Java java.nio.file.Files write() Method
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
Write an iterable collection of strings
Write an iterable collection of strings (using UTF-8 encoding)
Parameter Details
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: 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 existStandardOpenOption.CREATE_NEW: create a new file, fail if the file already existsStandardOpenOption.WRITE: open for writingStandardOpenOption.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.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.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
- Conciseness: compared to the traditional
FileOutputStreamandBufferedWriter, the code is more concise - Atomicity: the write operation is atomic; it either fully succeeds or fully fails
- Automatic Closing: no need to manually close the stream; the method handles it internally
- High Performance: the underlying implementation is optimized and performs well
Important Notes
- File Permissions: ensure the program has write permission for the target file
- File Locking: if the file is locked by another process, the write will fail
- Memory Limitations: when writing large files, loading all content at once may cause insufficient memory
- 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
for (String line : largeCollection) {
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
// Handle exception
}
Error Handling
AlwaysIOExceptionperform appropriate handling:
Example
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.
Other Extensions
Java java.nio.file.Files