java - 写入包含子文件夹的新文件时自动创建完整路径

标签 java path

<分区>

我想在当前不存在的文件夹中写入一个新文件。

我是这样使用的:

File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);

我在名为 dir1.dir2 的文件夹下获取文件 filename.txt

我需要dir1/dir2:

enter image description here

我怎样才能做到这一点?

请不要将此问题标记为重复,因为我在研究后没有得到我需要的东西。

更新 1

我正在使用 Jasper Report 和 Spring Boot 来导出 pdf 文件。

我需要在 当年 的目录下创建文件。在此文件夹下,我需要创建一个名为 当前月份 的目录,并在此目录下导出 pdf 文件。示例:

(2018/auguest/report.pdf )

我正在使用 LocalDateTime 获取 yearmonth

这是我的部分代码:

    ReportFiller reportFiller = context.getBean(ReportFiller.class);
    reportFiller.setReportFileName("quai.jrxml");
    reportFiller.compileReport();

    reportFiller = context.getBean(ReportFiller.class);
    reportFiller.fillReport();

    ReportExporter simpleExporter = context.getBean(ReportExporter.class);
    simpleExporter.setJasperPrint(reportFiller.getJasperPrint());

    LocalDateTime localDateTime = LocalDateTime.now();
    String dirName = simpleExporter.getPathToSaveFile() + "/"+ 
    localDateTime.getYear() + "/" + localDateTime.getMonth().name();
    File dir = new File(dirName);
    dir.mkdirs();
    String fileName = dirName + "/quaiReport.pdf";
    simpleExporter.exportToPdf(fileName, "");

这是我得到的:

enter image description here

最佳答案

尝试下面的代码,它会按照你的期望工作

File dir = new File("C:\\Users\\username\\Desktop\\dir1\\dir2");
dir.mkdirs();
File file = new File(dir, "filename.txt");
FileWriter newFile = new FileWriter(file);

您需要先创建文件夹结构,然后再创建文件

关于java - 写入包含子文件夹的新文件时自动创建完整路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51650187/

相关文章:

java - 动态创建对象时未找到类 - Java

java - 测试当指定文件不存在时应引发异常

java - 字符串连接不起作用

java - 关闭和重新打开 Realm 实例是否对性能不利?

python - IOError: [Errno 2] 没有这样的文件或目录

javascript - 绝对路径问题drupal

hadoop - 如何将多个零件文件放入路径

java - java 中的多线程未按预期工作

algorithm - 最宽路径问题有哪些应用?

python - 如何在 Python 脚本中的 MySQL 查询中使用变量路径