java 如何将 InputStream 输入 CSVReader?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25848991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:47:20  来源:igfitidea点击:

How do I feed an InputStream into a CSVReader?

javacsvinputstream

提问by user3011731

I want to convert InputStreaminto CSVReader. When I am using the code below

我想转换InputStreamCSVReader. 当我使用下面的代码时

CSVReader reader = new CSVReader(new FileReader(ADDRESS_FILE));

it is working fine, but, if I fetch the file from class path, then this code is not working.

它工作正常,但是,如果我从类路径中获取文件,则此代码不起作用。

How do I convert a InputStreamto CSVReader?

如何将 a 转换InputStreamCSVReader

This is not working cause InputStreamis not a string type:

这不起作用,原因InputStream不是字符串类型:

InputStream input = ImportCsv.class.getResourceAsStream("/dataUpload/staff.csv");
CSVReader reader = new CSVReader(new FileReader(input));

回答by Joop Eggen

CSVReader reader = new CSVReader(new InputStreamReader(input, "UTF-8"));

The bridge between binary bytes / InputStream, and unicode text (Reader/String) is the InputStreamReader. Specify the encoding of the bytes / InputStream if the file is not local.

二进制字节/InputStream 和Unicode 文本(Reader/String)之间的桥梁是InputStreamReader。如果文件不是本地文件,请指定字节/InputStream 的编码。

回答by Niru

Use

利用

CSVReader reader = new CSVReader(new InputStreamReader(input));


Edit to answer the comment

编辑以回答评论

The problem is because you don't have any constructor for FileReader as you want. See the FileReaderAPI for details. But since you will have to convert the byte stream to character stream so you will have to use InputStreamReader. For better performance you can wrap it with a BufferedReaderalso

问题是因为你没有任何你想要的 FileReader 构造函数。有关详细信息,请参阅FileReaderAPI。但是由于您必须将字节流转换为字符流,因此您必须使用InputStreamReader. 为了获得更好的性能,你可以用它包装BufferedReader