user2149122 user2149122 - 7 months ago 13
Java Question

Read float from a line throws ArrayIndexOutOfBoundsException

I have a .txt file in the format of an integer followed by a float and they are separated by the space character in every line. I want to read the float from every line and then put it in an array.
Here is my code so far, but when I run it it gives me a

ArrayIndexOutOfBoundsException


because I guess it never creates the second value:

BufferedReader reader = null;
try{
reader = new BufferedReader(new InputStreamReader(new FileInputStream(
new File(root.getAbsolutePath().toString()+"/samplefile.txt"))));
String line = null;
String[] numbers = null;
int i = 0;
value.clear();
while((line = reader.readLine()) != null){
numbers = line.split("/\\s/");
value.add(Float.valueOf(numbers[1].trim()));
}
mTextview5.setText(String.valueOf(value.get(1)));
}catch(IOException e){
e.printStackTrace();
}


So how can I go to second value?

Answer

Try with:

numbers = line.split("\\s+");