之前写过一个copy文件的方法,30多M要复制1分多钟.......想死,现在忘记了那个方法。只有下面这个方法
快速复制大文件、多个文件(包含文件夹):
public static void copyFile(File file, String dest) {
String pathWindows = file.getAbsolutePath() + File.separator;
String[] list = file.list();
for (String name : list) {
copy(pathWindows + name, dest + File.separator + name);
}
}
private static void copy(String src, String dest) {
BufferedInputStream reader = null;
BufferedOutputStream writer = null;
try {
File file = new File(src);
if (file.isDirectory()) {
File fileDir = new File(dest);
String tempStr = null;
int i = 0;
// 存在则重会命名
while (fileDir.exists()) {
i++;
tempStr = dest + "(" + i + ")";
fileDir = new File(tempStr);
}
if (fileDir.mkdirs())
copyFile(file, fileDir.getAbsolutePath());
} else {
reader = new BufferedInputStream(new FileInputStream(file));
writer = new BufferedOutputStream(new FileOutputStream(dest));
byte[] buff = new byte[reader.available()];
while ((reader.read(buff)) != -1) {
writer.write(buff);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.flush();
writer.close();
}
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试类:
public class Test {
public static void main(String[] args) {
// findFile("J:\\lhc");
copyFile();
}
public static void copyFile() {
File file = new File("D:\\temp\\Camera");
String pathWindows = file.getAbsolutePath() + "\\";
String[] list = file.list();
long millisRead = System.currentTimeMillis();
for (String name : list) {
copy(pathWindows + name, "D:\\temp\\新建文件夹\\" + name);
}
System.out.println("time = "
+ (System.currentTimeMillis() - millisRead) + "ms; 共:"
+ list.length + "个文件");
}
public static void copyFile(File file, String dest) {
String pathWindows = file.getAbsolutePath() + File.separator;
String[] list = file.list();
for (String name : list) {
copy(pathWindows + name, dest + File.separator + name);
}
}
private static void copy(String src, String dest) {
BufferedInputStream reader = null;
BufferedOutputStream writer = null;
try {
File file = new File(src);
if (file.isDirectory()) {
File fileDir = new File(dest);
String tempStr = null;
int i = 0;
// 存在则重会命名
while (fileDir.exists()) {
i++;
tempStr = dest + "(" + i + ")";
fileDir = new File(tempStr);
}
if (fileDir.mkdirs())
copyFile(file, fileDir.getAbsolutePath());
} else {
reader = new BufferedInputStream(new FileInputStream(file));
writer = new BufferedOutputStream(new FileOutputStream(dest));
byte[] buff = new byte[reader.available()];
while ((reader.read(buff)) != -1) {
writer.write(buff);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.flush();
writer.close();
}
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
如果您在编写java过程中有出现问题,如果不嫌弃小编我学历浅薄,欢迎添加我的微信一共讨论,感谢您的支持!微信号:atgeretg
觉得还可以请您打赏,您的十分满意是小编的无限动力。