java - 处理 FileReader 和 subString

标签 java substring filereader

我正在尝试读取一个文件.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()) {
        region = line.substring(0, 10);
        name = line.substring(10);
        System.out.println("" + region + name);
    }
    line = file.readLine();
}
file.close();

关于java - 处理 FileReader 和 subString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30958435/

相关文章:

javascript - readAsBinaryString() 无法正常工作

java - java应用程序在windows和os x上的可行性

MYSQL拆分并更新同一列的记录

java - 如何将对象从 servlet 传递到调用 JSP

regex - 使用Perl正则表达式获取URI的第二个字符串

sql-server - 如何在SQL Server中提取这个特定的子字符串?

java - 创建带有 FileDescriptor 的 FileReader 有何用处?

javascript - Angular2 - 从属性方法访问组件属性

java - Apache CXF 如何从根元素中删除 namespace

java - 如何在Java Canvas 中添加这个按钮?