Univocity Parsers - 代码不运行:线程“main”中的异常java.lang.NullPointerException

时间:2015-10-25 05:27:04

标签: parsing csv

我想解析.csv文件,我正在关注Univocity Parsers教程,并将他们的jar文件添加到依赖项here

发生空指针异常。

我想让Univocity Parsers工作,所以我可以看到它有多好,这是我在IntelliJ中运行的代码,非常感谢任何帮助,谢谢!

import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.IllegalStateException;
import java.lang.String;
import java.util.List;


public class UnivocityParsers {

public Reader getReader(String relativePath) {
    try {
        return new InputStreamReader(this.getClass().getResourceAsStream(relativePath), "Windows-1252");
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("Unable to read input", e);
    }
}

public void parseCSV(){

    CsvParserSettings settings = new CsvParserSettings();
    //the file used in the example uses '\n' as the line separator sequence.
    //the line separator sequence is defined here to ensure systems such as MacOS and Windows
    //are able to process this file correctly (MacOS uses '\r'; and Windows uses '\r\n').
    settings.getFormat().setLineSeparator("\r");

    // creates a CSV parser
    CsvParser parser = new CsvParser(settings);

    // parses all rows in one go.
    List<String[]> allRows = parser.parseAll(getReader("prodlist.csv"));

}

public static void main(String arg[]) {

    UnivocityParsers univocityParsers = new UnivocityParsers();

    univocityParsers.parseCSV();


}


}

堆栈追踪:

 Exception in thread "main" java.lang.NullPointerException   
 at java.io.Reader.<init>(Reader.java:78)
 at java.io.InputStreamReader.<init>(InputStreamReader.java:97)
 at UnivocityParsers.getReader(UnivocityParsers.java:15)
 at UnivocityParsers.parseCSV(UnivocityParsers.java:33)
 at UnivocityParsers.main(UnivocityParsers.java:41)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at        sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:497)
 at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

 Process finished with exit code 1

1 个答案:

答案 0 :(得分:1)

InputStreamReader找不到您的&#34; prodlist.csv&#34;文件。我怀疑它应该是&#34; /prodlist.csv"因为您似乎从resources文件夹中获取此文件。

在任何情况下,您都可以使用文件的完整路径来确保。添加此方法:

public Reader getFileReader(String absolutePath) {
    return new InputStreamReader(new FileInputStream(new File(absolutePath)), "UTF-8");
}

然后使用:

致电parser.parseAll
 List<String[]> allRows = parser.parseAll(getFileReader("c:/path/to/prodlist.csv"));