简体   繁体   English

在Java中读取CSV文件时为空行

[英]Blank lines when reading CSV file in Java

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. 我已经在Android上开发此应用程序已有一段时间了,尽管以前并不是很多次,但突然遇到了以下问题。

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. 我正在读取Java中的CSV文件,但是当我打印该CSV文件每一行的日志时,即使实际CSV文件中没有一行,也似乎有一个空白行。

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). 当我运行它时,我得到一个ArrayIndexOutOfBoundsException并在将日志信息打印到array.add(line[1]) ,在打印该行之前,我发现CSV文件中有一个空白行(当我检查了)。

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. array.add(line[1])是要抛出一个ArrayIndexOutOfBoundsException每次你有没有一个线时间, ...可能会试图读取它之前检查是一个好主意。 ie if(line.length > 1) { array.add(line[1]);} if(line.length > 1) { array.add(line[1]);}

Just doing this will fix multiple errors for you. 只是这样做会为您解决多个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM