如何解决 classloader.getResource() 方法的错误?
我处于一种奇怪的情况:
String filename ="file"+ System.currentTimeMillis()+file.getOriginalFilename();
// suppose the file name is "file123256chart.docx"
Path templatePath = Paths.get(DocTemplateProcessor.class.getClassLoader().getResource(filename).toURI());
这段代码给了我空指针异常,因为它无法归档资源。
但如果我写:
Path templatePath = Paths.get(DocTemplateProcessor.class.getClassLoader().getResource("file123256chart.docx").toURI());
它工作正常。打印文件名时,打印的结果完全相同。 任何人都知道为什么会发生这种情况?提前致谢。
更新 1:我遇到了问题,我将文件输入作为多部分文件。
public response getTextList(@RequestPart("file") MultipartFile file) {
String filename ="f"+ System.currentTimeMillis()+file.getOriginalFilename();
String filePath = "/home/ubuntu/templateEditor/learnspring/src/main/resources/" + filename;
java.nio.file.Files.copy(file.getInputStream(), Paths.get(filePath));
Path templatePath = Paths.get(DocTemplateProcessor.class.getClassLoader().getResource(filename).toURI());
因此,在第一个代码中,在将文件复制到我的服务器之前,templatePath 变量已被初始化。文件复制到我的服务器后,有什么方法可以运行该行吗?
I am in a strange situation :
String filename ="file"+ System.currentTimeMillis()+file.getOriginalFilename();
// suppose the file name is "file123256chart.docx"
Path templatePath = Paths.get(DocTemplateProcessor.class.getClassLoader().getResource(filename).toURI());
This code is giving me null pointer exception because it is not able to file the resource.
but if I write :
Path templatePath = Paths.get(DocTemplateProcessor.class.getClassLoader().getResource("file123256chart.docx").toURI());
It is working fine. On printing the file name, it prints exactly the same.
Anyone has any idea why this is happening ? Thanks in advance.
Update 1 : I got the problem, I was taking file input as multipart file.
public response getTextList(@RequestPart("file") MultipartFile file) {
String filename ="f"+ System.currentTimeMillis()+file.getOriginalFilename();
String filePath = "/home/ubuntu/templateEditor/learnspring/src/main/resources/" + filename;
java.nio.file.Files.copy(file.getInputStream(), Paths.get(filePath));
Path templatePath = Paths.get(DocTemplateProcessor.class.getClassLoader().getResource(filename).toURI());
So in the first code, templatePath variable was getting initialized before the file was getting copied to my server. Is there any way to run that line after the file got copied in my server ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用此示例来获取文件源,例如 srting:
You can use this example for take file souce like srting: