package com.zz.xd.ioService;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class IoService {
//copy()复制
//cut()剪切
//getdelete()删除文件夹内所有内容
//gettxt()获得txt中文本信息
//writetxt()输入txt
//filePath1为被复制文件的路径 filePath2为需要复制到的文件的路径)
public static void copy(String filePath1, String filePath2) {
String aimpath = filePath2;
File f1 = new File(filePath1);
File[] fs = f1.listFiles();
for (File temp : fs) {
if (temp.isDirectory()) {
aimpath = filePath2 + "/" + temp.getName();
File f2 = new File(aimpath);
f2.mkdirs();
copy(temp.getPath(), aimpath);
} else {
File f4 =new File(temp.getPath());
String text=gettxt(f4);
File f3 = new File(filePath2 + "/" + temp.getName());
try {
f3.createNewFile();
writetxt(f3, text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void cut(String filePath1, String filePath2) {
File f1 = new File(filePath1);
copy(filePath1, filePath2);
getDelete(f1);
}
private static void getDelete(File file) {
//生成File[]数组 listFiles()方法获取当前目录里的文件夹 文件
File[] files = file.listFiles();
//判断是否为空 //有没有发现讨论基本一样
if(files!=null){
//遍历
for (File file2 : files) {
//是文件就删除
if(file2.isFile()){
file2.delete();
}else if(file2.isDirectory()){
//是文件夹就递归
getDelete(file2);
//空文件夹直接删除
file2.delete();
}
}
}
}
private static String gettxt(File txt){
String text ="";
FileInputStream fileinput;
try {
fileinput = new FileInputStream(txt);
byte[] b=new byte[(int) txt.length()];
fileinput.read(b);
fileinput.close();
text=new String(b);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return text;
}
private static void writetxt(File txt,String text){
try {
FileOutputStream fileoutput = new FileOutputStream(txt);
byte[] b=text.getBytes();
fileoutput.write(b);
fileoutput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}`
基本思想:
复制:获取已有文件的文件名,在目标路径中进行拼接,再用新的路径新建文件夹或txt文件。用到的了递归的思想遍历文件夹。
剪切:与复制相同,然后通过delete方法删除已有文件。
delete方法若文件夹中有其他对象则无法删除,所以写了getdelete()方法用来判断是否含有子文件夹,然后删除文件夹内所有文件。
已知未解决问题:复制或剪切到子文件夹会导致死循环(无限新建文件夹)。