[英]Java: How to use Scanner class to read text file in resources folder
import java.util.*;
import java.io.File;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
File source;
Scanner input;
String name;
String id;
Pokemon x;
ArrayList<Pokemon> pokelist = null;
try {
source = new File("/resources/gen1pokemon.txt");
input = new Scanner(source);
input.useDelimiter(",");
while(input.hasNext()) {
id = input.next();
name = input.next();
x = new Pokemon(id,name);
pokelist.add(x);
input.nextLine();
}
} catch(Exception e) {
System.out.println(e);
}
System.out.println(pokelist.get(0).getName());
}
}
我的資源文件夾中有一個文本文件,我正在嘗試使用Scanner類讀取該文件,但是出現錯誤。 java.io.FileNotFoundException:\\ resources \\ gen1pokemon.txt(系統找不到指定的路徑)線程“ main”中的異常
任何想法可能是什么原因造成的? 我環顧四周,嘗試放置“ class.getResource(“文件名”)“引用,但是在聲明文件時也出現錯誤。
應用程序資源將在部署時成為嵌入式資源,因此明智的做法是立即開始訪問它們。 嵌入式資源必須通過URL而不是文件進行訪問。 查看信息。 有關如何形成URL的嵌入式資源的頁面 。
要在掃描器中使用URL,請從中獲取輸入流 ,然后使用new Scanner(InputStream)
。
您是否嘗試過/src/resources/gen1Pokemon.txt
?
路徑可能有些棘手,請根據項目的結構嘗試使用不同的版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.