1

Following is code:

public void storePartsFile(MultipartFile file, Long jobNumber) {
        Path path = Paths.get("C:\\DocumentRepository\\" +jobNumber + "\\Parts\\" + file.getOriginalFilename() );
        try {
            Files.write(path, file.getBytes());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Following is exception:

java.nio.file.NoSuchFileException: C:\DocumentRepository\12\Parts\b.pdf
    at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
    at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
    at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
    at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:230)
    at java.nio.file.spi.FileSystemProvider.newOutputStream(FileSystemProvider.java:434)
    at java.nio.file.Files.newOutputStream(Files.java:216)
    at java.nio.file.Files.write(Files.java:3292)

It looks for file on path and says no such file found.

This is new file i need to store at local.

Tried StandardOpenOption.CREATE_NEW but no effect.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
fatherazrael
  • 5,511
  • 16
  • 71
  • 155
  • If the directory containing the pdf does not exist, you may check [this](https://stackoverflow.com/questions/2833853/create-whole-path-automatically-when-writing-to-a-new-file) – samabcde Nov 22 '20 at 14:41

1 Answers1

0

The error indicates that C:\DocumentRepository\12\Parts isn't an existing directory. Files.write() will not make directories, no matter what you pass as standard open option.

Also your exception handling is broken. Fix your IDE template, that's just not okay. I've fixed that in the below snippet.

If your intent is to always create the directory if it doesn't yet exist:

public void storePartsFile(MultipartFile file, Long jobNumber) throws IOException {
        Path path = Paths.get("C:\\DocumentRepository\\" +jobNumber + "\\Parts\\" + file.getOriginalFilename() );
        Files.createDirectories(path.getParent());
        Files.write(path, file.getBytes());
}

NB: If you don't want your method to throw IOException (you're probably wrong on that, a method named 'savePartsFile' should definitely be throwing that), the right ¯\(ツ)/¯ I dunno how to deal with it code for an exception handler is throw new RuntimeException("Uncaught", e);, not what you have. throwing the runtimeexception means all relevant info about the error is preserved, and code execution stops, instead of just more or less silently chugging on, oblivious that errors have occurred.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72