Skip to content
Advertisement

How to get rid of – “java.io.IOException: The system cannot find the path specified”

I am trying to create a file and write to it, but I’m getting error in my path. Here is my code:

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

Advertisement

Answer

You can’t have a folder and a file with the same name in the same path location.

That’s why this code fails:

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

Here you’re first creating a folder, and then you’re attempting to create a file with the same path name. You need to choose a different name for the file.

I’m guessing you potentially intended the following instead:

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

I.e. create the parent folder of your file (including all its parents, as necessary), and then create the file inside it.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement