2010-12-13 205 views
6

我得到這個異常:使用此代碼FileNotFoundException異常(系統找不到指定的路徑)

java.io.FileNotFoundException: C:\...\filename.xml (The system cannot find the path specified) 

FileWriter fileWriter = new FileWriter(new File(path + date + time "filename.xml")); 
BufferedWriter writer = new BufferedWriter(fileWriter); 
writer.write("data"); 

路徑存在,但對於「日期」和「時間」需要的目錄被創建。應用程序對目錄具有完全權限。

任何想法?

回答

8

問題是因爲我正在創建一個子目錄來寫文件。所以,我現在有C:\example\,並希望寫C:\example\<date>\<time>\<files>

你需要在寫之前調用File#mkdirs()我的文件。

File file = new File("C:/example/newdir/newdir/filename.ext"); 
file.mkdirs(); 
// ... 
+0

中編寫我的文件,可以解決這個問題。非常感謝! – Michael 2010-12-13 14:25:29

4

是否假設電腦是正確的,而你錯了。

而且,在這種情況下,要寫入的目錄不會退出(或沒有權限這樣做)。

  1. 檢查從那裏
+0

是的,沒有另外的假設。問題是因爲我正在創建一個用於寫入文件的子目錄。所以我現在有C:\ example \並且想寫我的文件在C:\ example \ \

2

代碼當前工作目錄System.getProperty("user.dir")

  • 調試爲我工作。 (需要添加一個writer.close()供文本顯示在文件中。)

  • +0

    是的,在寫入存在的目錄時工作正常。剛發現問題是因爲我在不存在的子目錄中編寫。我目前有C:\ example \,並且想要在C:\ example \ \

    1

    您還需要將新創建的文件和文件夾路徑轉換爲字符串。

    File folder = new File("src\\main\\json\\", idNumber); 
        folder.mkdir(); 
    
        if (!folder.exists()) { 
         try { 
          folder.createNewFile(); 
         } catch (IOException ex) { 
          Logger.getLogger(JsonGeneration.class.getName()).log(Level.SEVERE, null, ex); 
         } 
        } 
        ... 
        ... 
        FileOutputStream output = null; 
         File file; 
         String content = data.toString(); 
    
         try { 
    
          String folder_location = folder.toString() + "\\"; 
          String filename = "CurrentInfo"; 
          file = new File(folder_location + filename.toString() + ".json"); 
          output = new FileOutputStream(file); 
    
          if (!file.exists()) { 
           file.createNewFile(); 
          } 
    
          byte[] content_in_bytes = content.getBytes(); 
    
          output.write(content_in_bytes); 
          output.flush(); 
          output.close(); 
    
         } catch (IOException ex) { 
          Logger.getLogger(JsonGeneration.class.getName()).log(Level.SEVERE, null, ex); 
         } finally { 
          try { 
           if (output != null) { 
            output.close(); 
           } 
          } catch (IOException e) { 
           Logger.getLogger(JsonGeneration.class.getName()).log(Level.SEVERE, null, e); 
          } 
         } 
    
        } 
    
    相關問題