Как создать файл в Java (не папка)? - PullRequest
13 голосов
/ 04 августа 2009

Возможно, это немного смущает, но через несколько часов я все еще не могу создать файл на 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;
}

Что мне здесь не хватает?

Ответы [ 2 ]

22 голосов
/ 04 августа 2009

Попробуйте сначала создать родительские каталоги:

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;
}
1 голос
/ 07 июня 2012
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;
         }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...