getResource() 到路径问题

getResource() to Path issue

在我的程序中有一行代码:

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);
}

试试这个:

String pathToFile = getClass().getResource("/data.txt").toString()).toPath(); 
String  pathToFile = pathToFile.replace("/C:", "C:/");
Path toRead = Paths.get(pathToFile)