本案例采用第三方 jar 包完成,commons-io-2.5.jar,
這個 jar 對文件操作非常方便,大家可以嘗試使用一下。
這里貼一個簡單的 demo 供大家使用
import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; public class MyFileUtils { public static void main(String[] args) throws IOException { String srcPath = "F:/copyFile/src"; String destPath = "F:/copyFile/dest123"; copyFile(srcPath, destPath); // copyDirectory(srcPath, destPath); // readFileToString(srcPath); } // 創建文件夾 public static void makeDir(String destPath) { File newFilePath = new File(destPath); if (!newFilePath.exists()) { newFilePath.mkdirs(); } } // 復制文件夾及其內容 public static void copyDirectory(String srcPath, String destPath) throws IOException { File file = new File(srcPath); makeDir(destPath); File destFile = new File(destPath); FileUtils.copyDirectory(file, destFile); } // 復制文件(應用場景:復制的同時更改文件名稱) public static void copyFile(String srcPath, String destPath) throws IOException { File src = new File(srcPath); makeDir(destPath); File[] srcFiles = src.listFiles(); if (srcFiles.length > 0) { for (File file : srcFiles) { String filename = file.getName(); if (file.isDirectory()) { copyFile(file.getAbsolutePath(), destPath); } if (filename.endsWith("html")) { int index = filename.indexOf("."); String newFileName = filename.substring(0, index) + "復制" + filename.substring(index); File destFile = new File(destPath + "/" + newFileName); FileUtils.copyFile(file, destFile); } } } } // 把文件 內容轉成字符串 public static void readFileToString(String srcPath) throws IOException { File src = new File(srcPath); File[] srcFiles = src.listFiles(); if (srcFiles.length > 0) { for (File file : srcFiles) { String filename = file.getName(); if (file.isDirectory()) { readFileToString(file.getAbsolutePath()); } if (filename.endsWith("html")) { String str = FileUtils.readFileToString(file, "utf-8"); System.out.println(str); } } } } }
簡單說明一下,
復制文件,包含文件夾 用到 FileUtils.copyDirectory(file, destFile);
復制單個文件 FileUtils.copyFile(file, destFile);
把文件內容讀取為字符串 FileUtils.readFileToString(file, "utf-8");