Forums Register Login

BufferedReader

+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
 

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:
Aaaaaand ... we're on the march. Stylin. Get with it tiny ad.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1748 times.
Similar Threads
Help! java.io.FileNotFoundException
FileNotFoundException,(help please)
Array IndexOutOfBounds Exception
help on comment lines
student record program
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 08:34:35.