2010-05-24 4 views
5

로 지정된 경로를 찾을 수 없습니다 :시스템은이 코드가 FileWriter

private static void saveMetricsToCSV(String fileName, double[] metrics) { 
     try { 
      FileWriter fWriter = new FileWriter(
        System.getProperty("user.dir") + "\\output\\" + 
        fileTimestamp + "_" + fileDBSize + "-" + fileName + ".csv" 
      ); 

      BufferedWriter csvFile = new BufferedWriter(fWriter); 

      for(int i = 0; i < 4; i++) { 
       for(int j = 0; j < 5; j++) { 
        csvFile.write(String.format("%,10f;", metrics[i+j])); 
       } 

       csvFile.write(System.getProperty("line.separator")); 
      } 

      csvFile.close(); 
     } catch(IOException e) { 
      System.out.println(e.getMessage()); 
     } 
    } 

을하지만이 오류를 얻을 : 왜

C:\Users\Nazgulled\Documents\Workspace\Só Amigos\output\1274715228419_5000-List-ImportDatabase.csv (The system cannot find the path specified)

어떤 생각을? 그 중요한 경우 내가 윈도우 7에 넷빈즈를 사용하고

...

+0

경로 및 파일이 있습니까? –

+2

부차적 인 점은 일반적으로 Path.Combine()을 사용하는 것이 좋습니다 ... –

+1

아니요,하지만 쓰지 않으려 고 시도 할 때 경로/파일이 자동으로 생성 될 것이라고 생각했습니다 ... –

답변

11

일반적으로 존재하지 않는 파일은 상위 디렉토리가있는 경우에만 Java에 의해 작성됩니다. 당신은 확인해야합니다 /디렉토리 트리를 만들 :

String filenameFullNoPath = fileTimestamp + "_" + fileDBSize + "-" 
     + fileName + ".csv"; 
    File myFile = new File(System.getProperty("user.dir") + File.separator 
     + "output" + File.separator + filenameFullNoPath); 
    File parentDir = myFile.getParentFile(); 
    if(! parentDir.exists()) 
     parentDir.mkdirs(); // create parent dir and ancestors if necessary 
    // FileWriter does not allow to specify charset, better use this: 
    Writer w = new OutputStreamWriter(new FileOutputStream(myFile),charset); 
+0

"myFile.getParentFile()"을 사용하여 "myFile.getParent()"(String을 반환)을 대체해야한다고 생각합니다. – Glennn

+0

@ 글렌 : 당신 말이 맞아요. – leonbloy

1

나는 "출력"디렉토리가 존재하지 않습니다 추측에는 요. 다음을 추가하십시오 :

new File(System.getProperty("user.dir") + File.separator + "output").mkdir(); 
1

당신은 getParentFile (Java Doc)는 부모 디렉토리가 있는지 확인하기 위해 사용할 수 있습니다. 다음은 상위 디렉토리가 있는지 점검하고 그렇지 않은 경우 작성합니다.

File myFile = new File(fileName); 
if(!myFile.getParentFile.exists()) { 
    myFile.getParentFile.mkdirs(); 
}