I've been working on this app in Android for a while now and suddenly encountered the following issue even though it has not been a problem many times before.
I am reading a CSV file in Java, but when I print a log of each line of that CSV file, there appears to be a blank line even though there is not one in the actual CSV file.
This is how I'm reading the file:
InputStreamReader inputStreamReader;
try {
inputStreamReader = new InputStreamReader(getActivity().getAssets().open("My_file.csv"));
Scanner inputStream = new Scanner(inputStreamReader);
inputStream.nextLine(); // Ignores the first line
while (inputStream.hasNext()) {
String data = inputStream.nextLine(); // Gets a whole line
String[] line = data.split(","); // Splits the line up into a string array
array.add(line[1]);
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
When I run it, I get an ArrayIndexOutOfBoundsException
and after putting in a log message before array.add(line[1])
which printed the line, I found that there was a blank line in my CSV file (and there wasn't when I checked it).
Any ideas?
First of All:
array.add(line[1])
is going to throw an ArrayIndexOutOfBoundsException
every time you have a line without a ,
... Might be a good idea to check for that before trying to read it. ie if(line.length > 1) { array.add(line[1]);}
Just doing this will fix multiple errors for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.