有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何自动创建丢失的文件夹?

在java中,我需要将一个字符串写入一个新文件,如“c:\test\upload\myfile”。txt”,如果“上载”文件夹不存在,它将自动创建它。怎么做?ApacheCommonsIO有这个API吗


共 (3) 个答案

  1. # 1 楼答案

    new File(fileToSave.getParent()).mkdirs();
    

    它返回一个布尔值,以检查制作是否成功(如果磁盘已满或文件名为“upload”等,则会失败)

  2. # 2 楼答案

    File file = new File(...);
    file.mkdirs(); //for several levels, without the "s" for one level
    FileWriter fileWriter = new FileWriter(file);
    fileWriter.write("...");
    

    Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

    Returns: true if and only if the directory was created, along with all necessary parent directories; false otherwise

    File.mkdirs()File.mkdir()

  3. # 3 楼答案

    除了公认的答案之外,由于问题还提到了Apache Common IO库,我在下面报告了一个使用该库的解决方案:

    File file = new File("...  the directory path ..."); 
    FileUtils.forceMkdir(file);
    

    这个解决方案使用来自包org.apache.commons.io的类^{}和方法^{},“生成一个目录,包括任何必要但不存在的父目录