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

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

我在这里错过了什么?

最佳答案

首先尝试创建父目录:

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

关于java - 如何在 java 中创建文件(不是文件夹)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1227650/

相关文章:

java - 如何删除打印行之间的空间?

java - 创建没有键值的 JsonArray

java - 使用 JPA 注释自动从父项中删除子项,从子项中自动删除父项

java - 为什么 C 和 Java 对 float 的舍入方式不同?

java - 使用 Spring Security 在 @WebMvcTest 中测试 JwtDecoder

Java 事件监听器

java - MKS124814 : Cannot show view information: View is unsupported in the Integration API

java - 比较两个键之间的差异不使用CompareTo java

java - 如何解析 IPV4 和 IPV6 的数据库连接字符串

java - 添加第二个 API 时 GoogleApiClient 崩溃