2010-05-24 40 views
5

tôi có mã này:Hệ thống không thể tìm ra con đường chỉ định với 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()); 
     } 
    } 

Nhưng tôi nhận được lỗi này:

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

Bất cứ ý tưởng tại sao?

Tôi đang sử dụng NetBeans trên Windows 7 nếu có vấn đề ...

+0

đường dẫn và tệp đó có tồn tại không? –

+2

cũng là điểm nhỏ, nó thường là hình thức tốt để sử dụng Path.Combine() ... –

+1

Không, nhưng khi tôi đang cố gắng viết và không đọc, tôi nghĩ đường dẫn/tập tin sẽ được tạo tự động ... –

Trả lời

11

Nói chung, tệp không tồn tại sẽ được tạo bởi Java chỉ khi thư mục gốc tồn tại. Bạn nên kiểm tra/tạo cây thư mục:

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

Tôi nghĩ rằng bạn có thể cần phải thay thế "myFile.getParent()" (trả về một String) với "myFile.getParentFile()". – Glennn

+0

@Glenn: bạn đã đúng, đã sửa – leonbloy

1

Tôi đoán rằng thư mục "đầu ra" không tồn tại. Hãy thử thêm:

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

Bạn có thể sử dụng getParentFile (Java Doc) để đảm bảo rằng các thư mục cha tồn tại. Sau đây sẽ kiểm tra xem thư mục gốc có tồn tại hay không và tạo nó nếu nó không có.

File myFile = new File(fileName); 
if(!myFile.getParentFile.exists()) { 
    myFile.getParentFile.mkdirs(); 
} 
Các vấn đề liên quan