写个自动备份文件的程序,网上抄了个方法并小改了下:
public static boolean copyFileUsingFileChannels(File source, File dest) throws IOException {
boolean scu;
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
inputChannel = new FileInputStream(source).getChannel();
outputChannel = new FileOutputStream(dest).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
scu = true;
} catch (Exception e) {
scu = false;
}finally {
inputChannel.close(); //报错里的54行
outputChannel.close();
}
return scu;
}
复制方法:
static int fail = 0;
static int error = 0;
public static void fileCopy(File file1, File file2) throws IOException {
File[] files1 = file1.listFiles();
if(files1 == null) { //如果是系统保护文件夹,files1为null
error ++; //计数:出错
return;
}
for (int i = 0; i < files1.length; i++) {
if (files1[i].isDirectory()) {
String s = files1[i].getName();
File file = new File(file2.getPath() + "/" + s);
file.mkdir();
fileCopy(files1[i], file); //递归
} else if (files1[i].isFile()) {
System.out.println(files1[i].getPath()); //输出当前文件路径
String str = files1[i].getPath().substring(
file1.getPath().length(),
files1[i].getPath().length());
//GFile为粘贴路径
File GFile = new File(file2.getPath() + "\\" + str);
/**
* 省略部分:检测是否为相同文件,相同则continue;
*/
if(!Test.copyFileUsingFileChannels(files1[i], GFile)) //报错里的74行
fail++; //计数:复制失败
}
}
}
现在对于系统保护文件夹能直接跳过,但单个文件比如pagefile.sys不知道怎么跳过,还是会报错
h:\pagefile.sys
Exception in thread "main" java.lang.NullPointerException
at bag.Test.copyFileUsingFileChannels(Test.java:54)
at bag.CopyFiles.fileCopy(CopyFiles.java:74)
at bag.CopyFiles.main(CopyFiles.java:89)