如何在java(不是文件夹)中创建文件?

Ger*_*ard 15 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;
}
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么?

bru*_*nde 23

首先尝试创建父目录:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • Java应该如何做到这一点?什么是"a",文件或目录?为什么"foo.dat"应该是文件而不是目录?你必须告诉Java你想要什么.如果您告诉Java创建一个名为"index.html"的目录,它将很乐意创建一个名为"index.html"的目录.:) (2认同)