JAVA拷贝文件

呵呵,好久没写博客了,今天碰到了一个问题,要拷贝一个文件,本来想到网上找找,结果发现都没有写的特别精简的,可能公司网络有限制的原因吧,就只能自己写一个精简的了。

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(); } } }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值