0

I am saving a string as a file.

import java.nio.file.Files;
import java.nio.file.Path;

String data = "hello, world";
Files.writeString(Path.of("upload-dir", "xyz", "abc", "data.txt"), data);

I get the following error as xyz and abc are not present.

java.nio.file.NoSuchFileException: upload-dir/xyz/abc/data.txt

Is there a way to get this method to create those directories as well automatically (not by calling Files.createDirectories(filePath.getParent());?

Saif
  • 2,530
  • 3
  • 27
  • 45
  • No. That is literally what createDirectories is for. – VGR Jul 05 '22 at 19:21
  • writeString also takes some options. So, I assumed it would be possible. – Saif Jul 05 '22 at 19:28
  • If you just want to create a single file (not directories) then use an [OpenOption](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/nio/file/StandardOpenOption.html) `Files.writeString(Path.of(path), data, StandardOpenOption.CREATE);` however, if you want to create an entire path you need to use `Files.createDirectories(path.getParent());` it's a simple matter to add a check if directories exist and call that before you attempt to write the file – sorifiend Jul 05 '22 at 22:03

0 Answers0