2011-08-17 32 views
2

我有一個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) 
+0

你的用戶名FSSD下運行呢? – asgs

+0

您確定'My Test'和'output'是文件而不是目錄 – vickirk

+0

My Test'是文件還是目錄?另外,你不需要顯式地調用'createNewFile()',因爲如果需要的話,創建一個'FileOutputStream'將會創建它。 –

回答

4

拒絕訪問與User Account Control做。基本上,您正在嘗試讀取您無權讀取的文件(請參閱文件屬性下的文件權限)。

您可以通過執行File.canRead()方法來查看該文件是否可讀。

if (infile.canRead()) { 
    //We can read from it. 

} 

要將其設爲可讀,可使用File.setReadable(true)方法。

if (!infile.canRead()) { 
    infile.setReadable(true); 
} 

或者,您可以使用java.io.FilePermission來提供文件讀取權限。

FilePermission permission = new FilePermission("C:\\Users\\FSSD\\Desktop\\My Test", "read"); 

或者

FilePermission permission = new FilePermission("C:\\Users\\FSSD\\Desktop\\My Test", FilePermission.READ); 
+0

我用你的代碼,我無法得到正確的輸出。我想,當我添加這個時,我犯了錯誤。如果你不介意根據你的代碼改變我的代碼, – Aerrow

+0

@BenDennison,我不知道你的目錄結構和你在做什麼。給我更多關於代碼在做什麼的信息。 –

+0

我的要求是,我想將文件從一個文件夾移到另一個文件夾。這是「C:/ MyTest」,在MyTest文件夾中我有一個文件名「ExampleFile.file」。在這裏,我必須將「ExampleFile.java」移動到「C:/ OutPut」文件夾中。如果有可能使用我的代碼做到這一點,否則任何替代方法來做到這一點。提前致謝 – Aerrow

0

我會把我的目錄中的文件,是不是在用戶/ ...

嘗試把你的文件在C:/ mytest,這時/