To create a file and write to it in Java, you can use either the traditional java.io
classes or the modern java.nio.file
API. Here are two common approaches:
1. Using java.io
(FileWriter/BufferedWriter)
Steps:
- Use
FileWriter
orBufferedWriter
for writing text. - Wrap in a
try-with-resources
statement to ensure resources are closed automatically. - Handle
IOException
.
Example:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileExample {
public static void main(String[] args) {
String content = "Hello, World!";
String filePath = "example.txt";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
writer.write(content);
System.out.println("File written successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Notes:
- Default Encoding:
FileWriter
uses the platform’s default charset. For explicit encoding, use:
new OutputStreamWriter(new FileOutputStream(filePath), StandardCharsets.UTF_8)
- Appending: Use
new FileWriter(filePath, true)
to append instead of overwrite.
2. Using java.nio.file
(Files.write)
Steps:
- Use
Files.write()
from the NIO API for simplicity. - Specify the file path (
Path
), content, and optional options (e.g.,StandardOpenOption
).
Example:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
public class WriteFileNIOExample {
public static void main(String[] args) {
String content = "Hello, World!";
Path path = Paths.get("example.txt");
try {
// Write bytes (converts String to UTF-8 bytes by default)
Files.write(path, content.getBytes());
// Or write lines (List<String>)
// Files.write(path, Arrays.asList("Line 1", "Line 2"));
System.out.println("File written successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Notes:
- Charset: Specify encoding explicitly if needed:
Files.write(path, content.getBytes(StandardCharsets.UTF_8));
- Options: Use
StandardOpenOption.CREATE
,StandardOpenOption.APPEND
, etc.:
Files.write(path, content.getBytes(), StandardOpenOption.APPEND);
- Create Directories: Ensure parent directories exist first:
Path dir = Paths.get("myfolder");
if (!Files.exists(dir)) {
Files.createDirectories(dir);
}
Key Differences
Feature | java.io (FileWriter) | java.nio.file (Files.write) |
---|---|---|
Simplicity | Requires more boilerplate. | Concise one-liner. |
Encoding Control | Requires OutputStreamWriter for explicit encoding. | Supports charset via overloaded methods. |
Appending | Use FileWriter(filePath, true) . | Use StandardOpenOption.APPEND . |
Exception Handling | Manual try-catch . | Manual try-catch . |
Performance | Buffered writing is efficient for large data. | Optimized for simplicity and small writes. |
Best Practices
- Use
try-with-resources
forjava.io
classes to prevent resource leaks. - Prefer
java.nio.file
for modern code (simpler and more flexible). - Handle exceptions (e.g.,
IOException
,SecurityException
).
Choose the method that best fits your use case and Java version!