2009-08-04 41 views
12

Có lẽ hơi lúng túng, nhưng sau vài giờ tôi vẫn không thể tạo ra một tập tin trong Java ...Cách tạo tệp trong java (không phải thư mục)?

File file = new File(dirName + "/" + fileName); 
try 
{ 
    // --> ** this statement gives an exception 'the system cannot find the path' 
    file.createNewFile(); 
    // --> ** this creates a folder also named a directory with the name fileName 
    file.mkdirs(); 
    System.out.println("file != null"); 
    return file; 
} 
catch (Exception e) 
{ 
    System.out.println(e.getMessage()); 
    return null; 
} 

tôi đang thiếu gì ở đây?

Trả lời

20

Hãy thử tạo các dirs mẹ đầu tiên:

File file = new File(dirName + File.separator + fileName); 
try { 
    file.getParentFile().mkdirs(); 
    file.createNewFile(); 
    System.out.println("file != null"); 
    return file; 
} 
catch (Exception e) 
{ 
    System.out.println(e.getMessage()); 
    return null; 
} 
+0

cảm ơn bạn, gây nhầm lẫn java mà dường như không phân biệt tập tin từ thư mục – Gerard

+2

Làm thế nào Java nên làm điều đó? "A", một tệp hoặc thư mục là gì? Tại sao “foo.dat” lại là một tệp chứ không phải một thư mục? Bạn phải nói với Java những gì bạn muốn. Nếu bạn yêu cầu Java tạo một thư mục có tên là "index.html", nó sẽ tạo một thư mục có tên là "index.html" một cách vui vẻ. :) – Bombe

+0

nhận xét của bạn xuất phát từ góc độ lập trình viên, sự nhầm lẫn của tôi là từ góc độ người dùng, bởi vì người dùng máy tính phân biệt giữa các thư mục và tệp; java có thể đã chọn để hỗ trợ con người, v.d. với một filetype enum – Gerard

1
String dirName="c:\\dir1\\dir2"; 
    String fileName="fileName.txt"; 
    File file = new File(dirName + "/" + fileName); 
    try { 
     new File(dirName).mkdirs(); // directory created here 
     file.createNewFile(); // file created here 
     System.out.println("file != null"); 
     return file; 
    }catch(Exception e) 
     { 
      System.out.println(e.getMessage()); 
      return null; 
     } 
Các vấn đề liên quan