我有一個Java代碼,用於將文件從一個文件夾複製到另一個文件夾。我用下面的代碼(我使用Windows 7操作系統),Java中的錯誤:java.io.FileNotFoundException:C: Users FSSD Desktop 我的測試(訪問被拒絕)
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下運行呢? – asgs
您確定'My Test'和'output'是文件而不是目錄 – vickirk
My Test'是文件還是目錄?另外,你不需要顯式地調用'createNewFile()',因爲如果需要的話,創建一個'FileOutputStream'將會創建它。 –