带有getPath的java.nio.file.InvalidPathException [英] java.nio.file.InvalidPathException with getPath

查看:126
本文介绍了带有getPath的java.nio.file.InvalidPathException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码

 String path =  getClass().getResource("Template.xls").getPath();

当我在计算机(Windows)上运行它时,一切都很好.我什至在get资源部分和get path部分都做了system.out.println,结果是:

When I run it on my machine (windows), everything is good. I even did system.out.println on the get resource part and on the get path part and the results were:

文件:/C:/Eclipse/Netbeans/SoftwareCom/build/classes/assets/Template.xls

file:/C:/Eclipse/Netbeans/SoftwareCom/build/classes/assets/Template.xls

/C:/Eclipse/Netbeans/SoftwareCom/build/classes/assets/Template.xls

/C:/Eclipse/Netbeans/SoftwareCom/build/classes/assets/Template.xls

但是我从一些用户那里得到了以下错误报告

However I am getting the following error reports from some users

java.nio.file.InvalidPathException: Illegal char <:> at index 4:
file:\C:\Software%20Com\SoftwareCom.exe!\assets\Template.xls

我不确定发生了什么,或者为什么对某些人而不是其他人有用

Iam not sure whats happening or why would it work for some and not others

有指针吗?

推荐答案

要正确回答此问题,知道要使用路径信息做什么将很有帮助.要读取文件,不需要路径.您可以致电

To answer this question properly, it would be helpful to know what you want to do with the path information. To read the file, you don't need the path. You could just call

getClass().getResourceAsStream("Template.xls")

如果您真的想知道路径,请致电

If you really want to know the path, you should call

URL url = getClass().getResource("Template.xls");
Path dest = Paths.get(url.toURI());

这可能会导致问题,因为您似乎将Java文件打包在Windows可执行文件中.参见 URL.getFile()中的错误

This might cause problems as you seem to pack your java files in a windows executable. See Error in URL.getFile()

编辑您的评论:

如上所述,您不需要复制源的路径.您可以使用

As I wrote above, you don't need the path of the source to copy. You can use

getClass().getResourceAsStream("Template.xls")

获取文件的内容并将内容写入您要写入的任何位置.失败的原因是第二个示例中的文件包含在可执行文件中:

to get the content of the file and write the content to whereever you want to write it. The reason for failing is that the file in your second example is contained within an executable file:

 file:\C:\Software%20Com\SoftwareCom.exe

从路径上可以看到:

file:\C:\Software%20Com\SoftwareCom.exe!\assets\Template.xls

感叹号指示资源在该文件内.它可以在Netbeans中工作,因为那里的资源不是打包在jar中,而是文件系统上的一个单独文件.您应该尝试在计算机上运行exe版本.它很可能也会失败.如果您需要更多信息或帮助,请提供完整的代码.

The exclamation mark indicates that the resource is within that file. It works within Netbeans because there the resource is not packed in a jar, but rather is a separate file on the filesystem. You should try to run the exe-version on your machine. It will most likely fail as well. If you want more information or help, please provide the complete code.

这篇关于带有getPath的java.nio.file.InvalidPathException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆