2009-08-04 3 views
12

아마도 다소 당황하지만, 일부 시간 후에 나는 아직도 내가 여기 실종 무엇 ...java (폴더가 아님)에서 파일을 만드는 방법은 무엇입니까?

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; 
} 

를 자바에서 파일을 만들 수 없습니다?

답변

20

먼저 부모 DIRS를 만들어보십시오 :

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

당신을 감사합니다, 그 자바를 혼동 자바 그렇게하는 방법 폴더 – Gerard

+2

에서 파일을 구별하지 않는 것? "a", 파일 또는 디렉토리 란 무엇입니까? "foo.dat"가 디렉토리가 아닌 파일이어야하는 이유는 무엇입니까? 자바에게 당신이 원하는 것을 말해야합니다. Java에 "index.html"이라는 디렉토리를 생성하라고 말하면 "index.html"이라는 이름의 디렉토리를 생성하게됩니다. :) – Bombe

+0

컴퓨터 사용자가 폴더와 파일을 구별하기 때문에 프로그래머의 관점에서 내 의견을 말하면서 혼란은 사용자의 관점에서 나온 것입니다. 자바는 인간을 지원하도록 선택할 수있었습니다. 파일 형식 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; 
     } 
관련 문제