如何摆脱 - "java.io.IOException: The system cannot find the path specified"

How to get rid of - "java.io.IOException: The system cannot find the path specified"

我正在尝试创建一个文件并写入其中,但我的路径出现错误。 这是我的代码:

@Value("${base.location}")
private String folderName;

if (StringUtils.isBlank(dateFileName)) {
            setdateFileName(new StringBuilder().append("MY_FILE")
                    .append(".txt").toString());
         
        }
        dateFile = new File(
                new StringBuilder().append(folderName).append(File.separator).append(dateFileName).toString());

        if (!dateFile.exists()) {
            try {
                dateFile.mkdir();
                dateFile.createNewFile(); //error
              
            }

同一路径位置不能有同名的文件夹和文件。

这就是此代码失败的原因:

dateFile.mkdir();
dateFile.createNewFile();

这里您首先创建了一个文件夹,然后您尝试创建一个具有相同路径名的文件。您需要为该文件选择一个不同的名称。

我猜你可能有以下意图:

dateFile.getParentFile().mkdirs();
dateFile.createNewFile();

即创建文件的父文件夹(必要时包括其所有父文件夹),然后在其中创建文件。