Java: Reading integers from a file into an array
File fil = new File("Tall.txt");
FileReader inputFil = new FileReader(fil);
BufferedReader in = new BufferedReader(inputFil);
int [] tall = new int [100];
String s =in.readLine();
while(s!=null)
{
int i = 0;
tall[i] = Integer.parseInt(s); //this is line 19
System.out.println(tall[i]);
s = in.readLine();
}
in.close();
I am trying to use the file "Tall.txt" to write the integers contained in them into the array named "tall". It does this to some extent, but also when I run it, it throws the following exception (:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at BinarySok.main(BinarySok.java:19)
Why exactly does it do this, and how do I remove it? As I see it, I read the file as strings, and then convert it to ints, which isn't illegal.
You might want to do something like this (if you're in java 5 & up)
Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt()){
tall[i++] = scanner.nextInt();
}
You must have an empty line in your file.
You may want to wrap your parseInt calls in a "try" block:
try {
tall[i++] = Integer.parseInt(s);
}
catch (NumberFormatException ex) {
continue;
}
Or simply check for empty strings before parsing:
if (s.length() == 0)
continue;
Note that by initializing your index variable i
inside the loop, it is always 0. You should move the declaration before the while
loop. (Or make it part of a for
loop.)
For comparison, here is another way to read the file. It has one advantage that you don't need to know how many integers there are in the file.
File file = new File("Tall.txt");
byte[] bytes = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bytes);
fis.close();
String[] valueStr = new String(bytes).trim().split("\\s+");
int[] tall = new int[valueStr.length];
for (int i = 0; i < valueStr.length; i++)
tall[i] = Integer.parseInt(valueStr[i]);
System.out.println(Arrays.asList(tall));
It looks like Java is trying to convert an empty string into a number. Do you have an empty line at the end of the series of numbers?
You could probably fix the code like this
String s = in.readLine();
int i = 0;
while (s != null) {
// Skip empty lines.
s = s.trim();
if (s.length() == 0) {
continue;
}
tall[i] = Integer.parseInt(s); // This is line 19.
System.out.println(tall[i]);
s = in.readLine();
i++;
}
in.close();
You might have confusions between the different line endings. A Windows file will end each line with a carriage return and a line feed. Some programs on Unix will read that file as if it had an extra blank line between each line, because it will see the carriage return as an end of line, and then see the line feed as another end of line.