基於 java.io.File 與流 API 的文件操作是 Java 開發基礎技能。本文匯總創建文件/目錄、讀寫文本/二進制、文件複製、遞歸遍歷刪除等高頻場景的標準化代碼範例,採用 Try-with-resources 確保資源安全釋放。
public void createFileIfNotExists(String path) throws IOException {
File file = new File(path);
if (!file.exists()) {
// 確保父目錄存在
file.getParentFile().mkdirs();
boolean created = file.createNewFile();
System.out.println("文件創建: " + created);
}
}
public void createDirs(String path) {
File dir = new File(path);
if (!dir.exists()) {
boolean created = dir.mkdirs(); // 遞歸創建
System.out.println("目錄創建: " + created);
}
}
mkdir() vs mkdirs():mkdir()僅創建最後一級,父目錄必須存在;mkdirs()遞歸創建所有不存在的父目錄,推薦始終使用 mkdirs()。
public String readTextFile(String path) throws IOException {
StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append(System.lineSeparator());
}
}
return content.toString();
}
// 覆蓋模式
public void writeTextFile(String path, String content) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(path))) {
writer.write(content);
}
}
// 追加模式
public void appendTextFile(String path, String content) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(path, true))) {
writer.write(content);
writer.newLine();
}
}
public void copyBinaryFile(String srcPath, String destPath) throws IOException {
File src = new File(srcPath);
if (!src.exists() || src.isDirectory()) {
throw new FileNotFoundException("源文件不存在: " + srcPath);
}
File dest = new File(destPath);
dest.getParentFile().mkdirs();
try (FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dest)) {
byte[] buffer = new byte[8192]; // 8KB
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
}
public void listAllFiles(File dir, Listresult) { if (dir == null || !dir.exists()) return; if (dir.isFile()) { result.add(dir); } else { File[] children = dir.listFiles(); if (children != null) { for (File child : children) { listAllFiles(child, result); } } } } // 使用示例 List allFiles = new ArrayList<>(); listAllFiles(new File("D:/data"), allFiles); allFiles.forEach(f -> System.out.println(f.getAbsolutePath()));
public void deleteRecursively(File file) {
if (file == null || !file.exists()) return;
if (file.isDirectory()) {
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
deleteRecursively(child);
}
}
}
boolean deleted = file.delete();
if (!deleted) {
System.err.println("刪除失敗: " + file.getAbsolutePath());
}
}
lines = Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);
// 寫入文件
Files.write(Paths.get("out.txt"), "內容".getBytes(StandardCharsets.UTF_8));
// 複製文件
Files.copy(Paths.get("src"), Paths.get("dest"), StandardCopyOption.REPLACE_EXISTING);
// 遞歸刪除
Files.walkFileTree(Paths.get("dir"), new SimpleFileVisitor() {
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file); return FileVisitResult.CONTINUE;
}
@Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir); return FileVisitResult.CONTINUE;
}
});
try-with-resources 自動關閉流(Java 7+)。exists()、isDirectory(),異常拋出具體信息。File 構造器或 Paths.get(),避免手動拼接分隔符。BufferedInputStream/BufferedOutputStream 或 NIO FileChannel)。java.nio.file.Files API,功能更強、異常更精確、支持符號鏈接與異步操作。