封装文件读取、写入,文件拷贝与文件夹拷贝

时间:2021-12-11 21:37:55

封装类:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/*
* 封装文件读取、写入,拷贝与文件夹的拷贝
*/

public class FileUtil {
//读取文件
public static String readfile(File src,File dest) {
return readfile(src.getAbsoluteFile(),dest.getAbsoluteFile());
}
public static String readfile(String src,String dest) {
String retString = "";
//1、建立关联
File file = new File(src);
//2、选择流
InputStream stream = null;
try {
stream = new FileInputStream(file);
//3、确定一次读取字节大小
byte[] size = new byte[1024];
int len = 0;//每次读取字节数
//4、循环读取
while(-1!=(len = stream.read(size))){//读取失败返回-1
String info = new String(size,0,len);
retString += info;
if(null!=dest){
writefile(dest,size);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(stream!=null){
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return retString;
}

//写出文件
public static void writefile(String dest,String str) {
writefile(dest,str.getBytes());
}
public static void writefile(String dest,byte[] size) {
File file = new File(dest);
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
OutputStream stream = null;
try {
stream = new FileOutputStream(file,true);
//字符串转字符数组
stream.write(size,0,size.length);
stream.flush();//强制刷新出去
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(null!=stream){
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//拷贝文件
public static void copyFile(File src,File dest) {
copyFile(src.getAbsoluteFile(),dest.getAbsoluteFile());
}
public static void copyFile(String src,String dest) {
readfile(src, dest);
}
//拷贝文件夹
public static void copyDir(String src,String dest) {
File srcData = new File(src);
File desData = null;
if(srcData.isDirectory()){
desData = new File(dest,srcData.getName());
}
copyDirdetails(srcData,desData);
}
private static void copyDirdetails(File src,File dest) {
if(src.isFile()){//文件
CopyFile.copyFile(src.getAbsolutePath(), dest.getAbsolutePath());
}else{
if(src.isDirectory()){//文件夹
//确保目标文件夹存在
dest.mkdirs();
//获取下一级目录|文件
for(File sub:src.listFiles()){
copyDirdetails(sub,new File(dest,sub.getName()));
}
}
}
}
}

测试类:

public class FileUtiltest {
public static void main(String[] args) {
FileUtil.copyFile("E:/test.txt", "D:/a.txt");
System.out.println(FileUtil.readfile("E:/test.txt", null));
FileUtil.writefile("E:/d.txt", "my name is hu cheng peng.");
FileUtil.copyDir("D:/JAVA/Workspaces/MyEclipse 8.6/SloarModel", "E:/");
}
}