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

2024-01-25

也许有点尴尬,但几个小时后我仍然无法用 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;
}

我在这里缺少什么?


首先尝试创建父目录:

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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在java中创建文件(而不是文件夹)? 的相关文章

随机推荐