我试图读取一个文件.txt
,该文件包含不同地区的8行商店。每行有15个字符。当我运行此代码时,只打印第一行,然后抛出此代码:
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
答案 0 :(得分:2)
你不要跳过空行。试试这个:
"
答案 1 :(得分:1)
我在子串
之前检查了线的长度String line = "";
String region = "", name = "";
BufferedReader file = new BufferedReader(new FileReader("Stores.txt"));
line = file.readLine();
while (line != null) {
if (!line.isEmpty()&&line.length() >= 15) {
region = line.substring(0, 10);
name = line.substring(10);
line = file.readLine();
System.out.println("" + region + name);
}
}
file.close();