Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

BufferedReader  RSS feed

 
Eibhlin Reid
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have created a .txt file that contains several lines of text. Ideally what I would like to do is to withdraw only certain substrings from the file, but I am getting two errors, which are: "java.lang.String.substring(Unknown Source)" and "java.lang.StringIndexOutOfBoundsException: String index out of range: 12". My code so far looks like this

public class TestBufferedReader {
static String inString;

public static void main(String[] args) throws Exception {
FileReader fileReader = new FileReader("list.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
try{
while ((inString = bufferedReader.readLine().substring(0,12)) != null){
System.out.println(inString);
}
}
catch (NullPointerException ex){
ex.printStackTrace();
}
catch (StringIndexOutOfBoundsException siobex){
siobex.printStackTrace();
}
fileReader.close();

}
}

Anybody know what I'm doing wrong?
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Eibhlin Reid:
With this expression you are assuming that every line you read from the file is at least 12 characters long. When your assumption fails, so does your program. As well, even if your assumption was always correct, you'd get a NullPointerException (which you catch) when you reached the end of the file. Try this:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!