我正在嘗試讀取文件.txt
,其中包含8行商店在不同地區。每行有15個字符。當我運行這段代碼,就在第一行印刷,之後它拋出這樣的:處理FileReader和子字符串
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 10
at java.lang.String.substring(String.java:1951)
String line = "";
String region = "", name = "";
BufferedReader file = new BufferedReader(new FileReader("Stores.txt"));
line = file.readLine();
while (line != null) {
region = line.substring(0, 10);
name = line.substring(10);
line = file.readLine();
System.out.println("" + region + name);
}
file.close();
文件:
Montrèal 16890
New York 27659
Pittsburg 26657
California 11201
Virginia 32945
Seattle 33981
Colorado 10345
請過帳文本文件的內容。 –
你試過調試你的代碼嗎?你確定每行至少包含10個字符嗎?沒有空行(例如在文件末尾)? – Pshemo
你的文件似乎在文本行之間有空行。您需要跳過解析該行的部分。 – Pshemo