爪哇蔚来 |路径和文件 |如何创建具有从其他对象获取的自定义名称的自定义文件和文件夹?



以下是代码:

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:DocumentRepository12Partsb.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:DocumentRepository12Parts不是现有目录。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意味着有关错误的所有相关信息都会被保留下来,代码执行也会停止,而不是或多或少地悄无声息地继续执行,忘记错误已经发生。

最新更新