Java 蔚来 |路径和文件 |如何使用从其他对象获取的自定义名称创建自定义文件和文件夹?

Java NIO | Paths & Files | How to create custom file and folder with custom name fetched from other object?

代码如下:

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();
        }

以下是例外情况:

java.nio.file.NoSuchFileException: C:\DocumentRepository\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)

它在路径上查找文件,但说没有找到这样的文件。

这是我需要存储在本地的新文件。

试过StandardOpenOption.CREATE_NEW但没有效果。

错误表明 C:\DocumentRepository\Parts 不是现有目录。 Files.write() 不会创建目录,无论您作为标准打开选项传递什么。

你的异常处理也被破坏了。修复您的 IDE 模板,那是不行的。我在下面的代码片段中修复了这个问题。

如果您的意图是在目录尚不存在时始终创建该目录:

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());
}

注意:如果你不希望你的方法抛出 IOException(你可能错了,一个名为 'savePartsFile' 的方法肯定会抛出那个),正确的¯\(ツ)/¯ 我不知道如何处理异常处理程序的代码是 throw new RuntimeException("Uncaught", e);,而不是你所拥有的。抛出 runtimeexception 意味着所有关于错误的相关信息都被保留,代码执行停止,而不是或多或少地默默地继续,忘记了错误的发生。