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

4smxwvx5  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(346)

以下是代码:

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\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)

它在路径上查找文件,并说找不到这样的文件。
这是我需要在本地存储的新文件。
尝试了standardopenoption.create\u new,但没有效果。

mu0hgdu0

mu0hgdu01#

错误表明 C:\DocumentRepository\12\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”的方法肯定应该抛出ioexception),那么¯(ツ)/¯ 我不知道如何处理它,异常处理程序的代码是 throw new RuntimeException("Uncaught", e); ,不是你所拥有的。抛出runtimeexception意味着保留所有有关错误的信息,代码执行停止,而不是或多或少地默默地继续,忘记错误已经发生。

相关问题