java文件夹内文件迁移_(原)Java实现拷贝文件(含文件夹内所文件)

前些天写了个例子((原)Java拷贝文件的例子(使用channel实现)),通过java代码实现了简单的拷贝文件功能,但仅仅是实现的是单个文件,并不满足实际应用上的一些功能,因此在此基础上又”改造”了一下,算是完善吧,代码如下:

1.copyFile(拷贝单个文件方法)

public static void copyFile(String sourceDir, String targetDir)

throws IOException {

File fileIn = new File(sourceDir);

FileInputStream in = new FileInputStream(fileIn);

FileChannel fileChannelIn = in.getChannel();

File fileOut = new File(targetDir);

if (!fileOut.exists()) {

if (fileOut.isDirectory()) {

fileOut.mkdirs();

} else {

fileOut.getParentFile().mkdirs();

fileOut.createNewFile();

}

}

FileOutputStream out = new FileOutputStream(new File(targetDir));

FileChannel fileChannelout = out.getChannel();

ByteBuffer buffer = ByteBuffer.allocate(1024 * 2);

while (true) {

buffer.clear();

int r = fileChannelIn.read(buffer);

if (r <= 0) {

break;

}

buffer.flip();

fileChannelout.write(buffer);

}

}

2.copyDir(“拷贝”文件夹方法)

这里所说的”拷贝”其实只是在指定目录下创建文件夹,因为文件夹并不需要源文件的内容,故只创建即可.

public static void copyDir(String targetDir) throws IOException {

File file = new File(targetDir);

if (!file.exists()) {

file.mkdirs();

}

}

3.copyFiles(拷贝文件包括文件夹下的所有文件)

public static void copyFiles(String sourceDir, String targetDir)

throws IOException {

File soreceFile = new File(sourceDir);

if (soreceFile.exists()) {

if (soreceFile.isDirectory()) {

File[] files = soreceFile.listFiles();

for (File file : files) {

System.out.println(file.getName());

if (file.isFile()) {

copyFile(sourceDir + File.separator + file.getName(),

targetDir + File.separator + file.getName());

} else if (file.isDirectory()) {

copyDir(targetDir + File.separator + file.getName());

copyFiles(sourceDir + File.separator + file.getName(),

targetDir + File.separator + file.getName());

}

}

} else if (soreceFile.isFile()) {

copyFile(sourceDir + File.separator + soreceFile.getName(),

targetDir + File.separator + soreceFile.getName());

}

} else {

throw new FileNotFoundException("源文件不存在:"

+ soreceFile.getCanonicalPath());

}

}

该方法递归的调用了方法本身,这就实现了拷贝所有文件了.经过测试,方法是可行的.

测试的文件目录结果为:

-/lib/

–/lib/a/

—lib/a/aa/

—lib/a/aa.txt

–lib/b/

–lib/a.txt

之前在写的时候空文件b就没有”拷贝”成功,经后来检测发现少了个判断,当是空文件夹的时候没有”拷贝”,而如果是文件夹下有文件时,在创建文件的时候会连同其父文件夹一起创建,因此要分开来创建.

附带源文件:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值