![](/img/trans.png)
[英]How to check folder size or containing files in Java without knowing the file name with java.nio.file?
[英]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\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_NEW 但没有效果。
该错误表明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' 的方法肯定会抛出那个),正确的¯\\ (ツ) /¯ 我不知道如何处理异常处理程序的代码是throw new RuntimeException("Uncaught", e);
,不是你所拥有的。 抛出 runtimeexception 意味着关于错误的所有相关信息都被保留,代码执行停止,而不是或多或少默默地继续,无视错误发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.