2009-08-04 15 views
12

はおそらくやや恥ずかしいが、いくつかの時間後、私はまだJavaでファイルを作成することはできません...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

はあなたに感謝し、そのJavaの混乱Javaがそれを行う必要がありますどのようにフォルダ – Gerard

+2

からファイルを区別していないようですか? "a"とは何か、ファイルやディレクトリは何ですか?なぜ "foo.dat"はディレクトリではなくファイルであるべきですか?あなたが望むものをJavaに伝えなければなりません。 Javaに "index.html"という名前のディレクトリを作成すると、 "index.html"という名前のディレクトリが作成されます。 :) – Bombe

+0

あなたの発言はプログラマーの視点から来ています。私の混乱は、ユーザーの視点からです。コンピューターユーザーがフォルダーとファイルを区別するためです。 Javaは人間をサポートすることを選択できました。ファイルタイプの列挙型を使用 – 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; 
     } 
関連する問題