Dealing with FileReader and subString

295 views Asked by At

I'm trying to read a file .txt which contains 8 lines of Stores in different regions. Each line has 15 characters. When I run this code, just the first line is printed and afterwards it throws this:

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();

File:

Montrèal   16890

New York   27659

Pittsburg  26657

California 11201

Virginia   32945

Seattle    33981

Colorado   10345
2

There are 2 answers

2
Franz Becker On BEST ANSWER

You don't skip over the empty lines. Try this one:

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();
3
Madhan On

I've checked the length of the line before substring

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();