java简单实现本地拷贝文件与拷贝文件夹
作者:互联网
初步学习,只是简单的写了一下,如有不足之处请大家提出,谢谢。
package util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @ClassName: FileUtil
* @Description: 文件工具类
* @author yxy
* @date 2021年4月7日
*/
public class FileUtil {
private static FileUtil copyFile;
private FileUtil() {
// TODO Auto-generated constructor stub
}
public static FileUtil getCopyFile() {
if (copyFile == null) {
synchronized (FileUtil.class) {
if (copyFile == null) {
copyFile = new FileUtil();
}
}
}
return copyFile;
}
/**
* @Title: copyFile
* @Description: 拷贝文件
* @param path 原文件路径
* @param newPath 保存路径
* @return
*/
public boolean copyFile(String path, String newPath) {
File inputFile = new File(path);
File outPutFile = new File(newPath);
BufferedInputStream bi = null;
BufferedOutputStream bo = null;
try {
FileInputStream fi = new FileInputStream(inputFile);
FileOutputStream fo = new FileOutputStream(outPutFile);
bi = new BufferedInputStream(fi);
bo = new BufferedOutputStream(fo);
byte data[] = new byte[100];
while (true) {
int rs = bi.read(data);
if (rs < 0) {
break;
}
bo.write(data, 0, rs);
}
bo.flush();
return true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (bo != null) {
try {
bo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (bi != null) {
try {
bi.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return false;
}
/**
* @Title: copyDirectory
* @Description: 拷贝文件夹
* @param Path 原文件夹路径
* @param newPath 保存路径
* @return
*/
public boolean copyDirectory(String path, String newPath) {
File nowDir = new File(path);
new File(newPath + "\\" + nowDir.getName()).mkdir();
File newDir = new File(newPath + "\\" + nowDir.getName());
File[] copyFiles = nowDir.listFiles();
for (File f : copyFiles) {
if (f.isDirectory()) {
copyDirectory(f.getAbsolutePath(), newDir.getAbsolutePath());
}
if (f.isFile()) {
copyFile(f.getAbsolutePath(), newDir.getAbsolutePath() + "\\" + f.getName());
}
}
return true;
}
}
标签:copyFile,java,文件夹,File,import,catch,new,拷贝 来源: https://blog.csdn.net/RENSRM/article/details/116243516