【发布时间】:2011-10-28 22:49:51
【问题描述】:
我有一个用于将文件从一个文件夹复制到另一个文件夹的 java 代码。我使用了以下代码(我使用的是Windows 7操作系统),
CopyingFolder.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class CopyingFolder {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
File infile=new File("C:\\Users\\FSSD\\Desktop\\My Test");
File opfile=new File("C:\\Users\\FSSD\\Desktop\\OutPut");
try {
copyFile(infile,opfile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void copyFile(File sourceFile, File destFile)
throws IOException {
if (!sourceFile.exists()) {
return;
}
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
当我使用上面的代码时,我得到了以下错误。为什么会出现?我该如何解决?
java.io.FileNotFoundException: C:\Users\FSSD\Desktop\My Test (Access is denied)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at CopyingFolder.copyFile(CopyingFolder.java:34)
at CopyingFolder.main(CopyingFolder.java:18)
【问题讨论】:
-
你是在 FSSD 用户名下运行这个吗?
-
你确定
My Test和output是文件而不是目录 -
My Test是文件还是目录?此外,您不需要显式调用createNewFile(),因为创建FileOutputStream会在必要时创建它。 -
@vickirk:是的,这些文件夹名称分别是源和目标
-
那么你的代码就是错误的:你应该检查它是否是一个目录,如果是则递归到它。打开
FileInputStream仅对文件有意义(即非目录)。
标签: java file windows-7 hidden