@JAVA使用File类复制文件
下面先贴代码
//在复制的时候遇到过很多问题
import java.io.*;
public class Exam5 {
public static void main(String[] args) throws Exception{
File fromDir = new File("D:\\temp\\a.txt");
File toDir = new File("D:\\temp1");
copyFile(fromDir,toDir);
}
public static void copyFile(File fromDir,File toDir) throws Exception {
if (!toDir.exists()){
toDir.mkdirs();
}
if (fromDir.isFile()){
FileInputStream fis = new FileInputStream(fromDir);
String[] str = fromDir.getAbsolutePath().split("\\\\");
String s = str[str.length-1];
FileOutputStream fos = new FileOutputStream(File.separator+toDir.getAbsolutePath()+File.separator+s );
if (!toDir.exists()){
toDir.mkdirs();
}
byte[] b = new byte[8192];
int n=0;
while ((n = fis.read(b)) != -1) {
fos.write(b, 0, n);
}
fis.close();
fos.close();
}else {
File[] listFiles = fromDir.listFiles();
for(File f:listFiles){
if(f.isFile()){
FileInputStream fis = new FileInputStream(f);
FileOutputStream fos = new FileOutputStream(new File(subFilePath(f, toDir, fromDir)));
byte[] b = new byte[8192];
int n=0;
while ((n = fis.read(b)) != -1) {
fos.write(b, 0, n);
}
fis.close();
fos.close();
}else {
File fileOut1 = new File(
toDir.getAbsolutePath() + f.getAbsolutePath().substring(fromDir.getAbsolutePath().length()));
fileOut1.mkdirs();
copyFile(f, fileOut1);
}
}
}
}
private static String subFilePath(File f, File fileOut, File fileIn) {
System.out.println(fileOut.getAbsolutePath() + f.getAbsolutePath().substring(fileIn.getAbsolutePath().length()));
return fileOut.getAbsolutePath() + f.getAbsolutePath().substring(fileIn.getAbsolutePath().length());
}
}
第一个问题就是File的listFiles()方法
当我File类传入的是一个文件的时候,listFiles()方法返回的是一个null,通过API来说就是出现了io异常(具体原因我也不是很清楚).
第二个问题就是String中split()方法的使用
split()方法在剪切类似于.与\的时候需要加上转义,给.进行转义要加上两个\,给File.separator进行转义的时候需要==\\==进行转义