簡體   English   中英

錯誤:`error - java.lang.IllegalArgumentException:從類路徑獲取文件時,URI不是分層的

[英]Error: `error - java.lang.IllegalArgumentException: URI is not hierarchical while getting a file from a classpath

我有一個包含在類路徑中的目錄中的文件。 它看起來像這個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);

我得到以下內容: -

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

我該如何解決這個問題?

如果您的調用類本身與文本文件位於同一個包中,只需使用:

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

更換

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM