呵呵,好久没写博客了,今天碰到了一个问题,要拷贝一个文件,本来想到网上找找,结果发现都没有写的特别精简的,可能公司网络有限制的原因吧,就只能自己写一个精简的了。
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /** * 专门用作文件处理,当前只是做了文件及文件夹拷贝。 * * @author jie.xiang * */ public class FileUtil { public final static int BYTE_LENGTH = 1024; public final static void copyFile(File sourceFile, File targetFolder) throws IOException { if (!sourceFile.exists() || !targetFolder.exists()) { return; } String targetName = targetFolder.getAbsolutePath() + File.separator + sourceFile.getName(); File targetFile = new File(targetName); if (sourceFile.isDirectory()) { if (!targetFile.exists()) { targetFile.mkdir(); } File[] children = sourceFile.listFiles(); for (File child : children) { copyFile(child, targetFile); } } else { copy(sourceFile, targetFile); } } /** * 将源文件的目录拷贝到目标文件。 * * @param sourceFile * @param targetFile * @throws IOException * * @author jie.xiang */ public static void copy(File sourceFile, File targetFile) throws IOException { if (!sourceFile.isFile() && !targetFile.exists()) { return; } FileInputStream in = new FileInputStream(sourceFile); FileOutputStream out = new FileOutputStream(targetFile); byte[] arr = new byte[BYTE_LENGTH]; int length = -1; while ((length = in.read(arr)) != -1) { out.write(arr, 0, length); } in.close(); out.flush(); } /** * 源文件以及目标文件目录 * * @param sourceFilePath * @param targetFolderPath * @throws IOException * * @author jie.xiang */ public final static void copyFile(String sourceFilePath, String targetFolderPath) throws IOException { File sourceFile = new File(sourceFilePath); File targetFolder = new File(targetFolderPath); copyFile(sourceFile, targetFolder); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { copyFile("E://工作区//Java//Java API", "D://Java API"); } catch (IOException e) { e.printStackTrace(); } } }