2010-12-13 64 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); 
          } 
         } 
    
        } 
    
    相关问题