错误:错误- . lang。IllegalArgumentException:在从类路径获取文件时,URI不具有层次结构

时间:2022-12-15 20:51:42

I have a file contained within a directory in a classpath. It looks like this pl/shenlon/io/gui/appData/file.txt. Now, when I try to convert it to a File and read with this code:

我有一个包含在类路径目录中的文件。它看起来像这个pl/shenlon/io/gui/appData/file.txt。现在,当我试着把它转换成一个文件,并阅读这个代码:

File cityNamesFile = new File(ClassLoader.getSystemResource("pl/shenlon/io/gui/appData/list.txt").toURI());
Scanner cns = new Scanner(cityNamesFile);

I get the following:-

我得到以下:-

error - java.lang.IllegalArgumentException: URI is not hierarchical.

错误——. lang。IllegalArgumentException: URI不是分层的。

How can I fix this problem?

我如何解决这个问题?

2 个解决方案

#1


7  

If your calling class is itself in the same package as the text file, just use :

如果您的调用类本身与文本文件在同一个包中,则只需使用:

InputStream is = getClass().getResourceAsStream("list.txt");
Scanner cns = new Scanner(is);

#2


6  

Replace

取代

File cityNamesFile = new File(ClassLoader.getSystemResource("pl/shenlon/io/gui/appData/list.txt").toURI());

with

File cityNamesFile = new File(Thread.currentThread().getContextClassLoader().getResource("pl/shenlon/io/gui/appData/list.txt").getFile());

#1


7  

If your calling class is itself in the same package as the text file, just use :

如果您的调用类本身与文本文件在同一个包中,则只需使用:

InputStream is = getClass().getResourceAsStream("list.txt");
Scanner cns = new Scanner(is);

#2


6  

Replace

取代

File cityNamesFile = new File(ClassLoader.getSystemResource("pl/shenlon/io/gui/appData/list.txt").toURI());

with

File cityNamesFile = new File(Thread.currentThread().getContextClassLoader().getResource("pl/shenlon/io/gui/appData/list.txt").getFile());