欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

java中使用递归方法删除_删除和拷贝文件递归方法(Java实现)

发布时间:2024/9/30 30 豆豆
生活随笔 收集整理的这篇文章主要介绍了 java中使用递归方法删除_删除和拷贝文件递归方法(Java实现) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

利用递归的方法删除和拷贝文件原理很简单:程序自己调用自己实现文件的删除和拷贝,代码如下:

import java.io.*;

public class Dptest {

//删除指定文件夹下的所有文件及根文件夹

public void deleteFile(String path) {

File f = new File(path);

if(f.isDirectory())

{

File[] file = f.listFiles();

for (File file2 : file) {

this.deleteFile(file2.toString());

file2.delete();

}

}else{

f.delete();

}

f.delete();

}

//拷贝整个文件夹的方法

public void copyFiles(String path1, String path2) throws Exception {

File file = new File(path1);

if(file.isDirectory()){

File f = new File(path2);

if(!f.exists()) f.mkdir();

File[] files = file.listFiles();

for (File file2 : files) {

//System.out.println(file2.toString()+"-----"+path2+"/"+file2.getName());

copyFiles(file2.toString(),path2+"/"+file2.getName());

}

}else{

copy(path1,path2);

}

}

//拷贝单个文件的方法

public void copy(String path1,String path2) throws IOException {

DataInputStream in = new DataInputStream(

new BufferedInputStream(

new FileInputStream(path1)));

byte[] date = new byte[in.available()];

in.read(date);

DataOutputStream out = new DataOutputStream(

new BufferedOutputStream(

new FileOutputStream(path2)));

out.write(date);

in.close();

out.close();

}

public static void main(String[] args) throws Exception {

Dptest dp = new Dptest();

dp.deleteFile("c:/xxx");

// dp.copyFiles("c:/yyy", "c:/zzz");

}

}

总结

以上是生活随笔为你收集整理的java中使用递归方法删除_删除和拷贝文件递归方法(Java实现)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。