在 Java 中读取 CSV 文件时出现空行
Blank lines when reading CSV file in Java
我在 Android 开发这个应用程序有一段时间了,突然遇到了以下问题,尽管之前多次都不是问题。
我正在读取 Java 中的 CSV 文件,但是当我打印该 CSV 文件每一行的日志时,似乎有一个空行,即使实际 CSV 文件中没有空行.
我是这样阅读文件的:
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();
}
当我 运行 它时,我得到一个 ArrayIndexOutOfBoundsException
并且在打印该行的 array.add(line[1])
之前输入一条日志消息后,我发现我的文件中有一个空行CSV 文件(我检查时没有)。
有什么想法吗?
首先:
array.add(line[1])
每次你有一行没有 ,
时都会抛出一个 ArrayIndexOutOfBoundsException
...在尝试阅读之前检查一下可能是个好主意.即 if(line.length > 1) { array.add(line[1]);}
只需执行此操作即可为您修复多个错误。
我在 Android 开发这个应用程序有一段时间了,突然遇到了以下问题,尽管之前多次都不是问题。
我正在读取 Java 中的 CSV 文件,但是当我打印该 CSV 文件每一行的日志时,似乎有一个空行,即使实际 CSV 文件中没有空行.
我是这样阅读文件的:
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();
}
当我 运行 它时,我得到一个 ArrayIndexOutOfBoundsException
并且在打印该行的 array.add(line[1])
之前输入一条日志消息后,我发现我的文件中有一个空行CSV 文件(我检查时没有)。
有什么想法吗?
首先:
array.add(line[1])
每次你有一行没有 ,
时都会抛出一个 ArrayIndexOutOfBoundsException
...在尝试阅读之前检查一下可能是个好主意.即 if(line.length > 1) { array.add(line[1]);}
只需执行此操作即可为您修复多个错误。