处理 FileReader 和 subString
Dealing with FileReader and subString
我正在尝试读取一个文件 .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
我检查了子字符串前的行的长度
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();
不要跳过空行。试试这个:
String line = "";
String region = "", name = "";
BufferedReader file = new BufferedReader(new FileReader("Stores.txt"));
line = file.readLine();
while (line != null) {
if (!line.isEmpty()) {
region = line.substring(0, 10);
name = line.substring(10);
System.out.println("" + region + name);
}
line = file.readLine();
}
file.close();
我正在尝试读取一个文件 .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
我检查了子字符串前的行的长度
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();
不要跳过空行。试试这个:
String line = "";
String region = "", name = "";
BufferedReader file = new BufferedReader(new FileReader("Stores.txt"));
line = file.readLine();
while (line != null) {
if (!line.isEmpty()) {
region = line.substring(0, 10);
name = line.substring(10);
System.out.println("" + region + name);
}
line = file.readLine();
}
file.close();