在我的程序中我有一行代码:
Path toRead = new File(getClass().getResource("/data.txt").toString()).toPath();
每当我尝试运行此程序时,都会收到错误:
Exception in thread "main" java.nio.file.InvalidPathException: Illegal char <:> at index 4
作为一个普通的文件,它似乎运行良好,但作为一个路径,它搞砸了,有解决办法吗?
我需要它作为路径才能使用Files.copy()
。
data.txt 所在的文件夹被添加为源文件夹。
最佳答案
您永远不应该假设从 getResource()
返回的 URL
引用的是文件。您应该只使用URL.openStream()
。这实际上就是 getResourceAsStream()
所做的。
try (InputStream is = getClass().getResourceAsStream("/data.txt")) {
Files.copy(is, targetPath);
}
关于java - getResource() 到 Path 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36000646/