我想要一个用户可以上传CSV文件的功能,其中的内容将被保存到数据库中。上传并保存到数据库中对我来说不是问题,而是如何读取CSV文件。我只对如何工作的文件狭窄的背景,我的一切都是这些代码:用Java读取CSV文件
InputStream file = item.getInputStream();
// How do I read it?
我想要一个用户可以上传CSV文件的功能,其中的内容将被保存到数据库中。上传并保存到数据库中对我来说不是问题,而是如何读取CSV文件。我只对如何工作的文件狭窄的背景,我的一切都是这些代码:用Java读取CSV文件
InputStream file = item.getInputStream();
// How do I read it?
对于读取CSV文件,你可以使用BufferedReader
类:
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream("CSV file location"))
);
之后,使用StringTokenizer
来读取文件中的每个常见的分隔值,例:
if(reader.readLine()!=null) {
StringTokenizer tokens = new StringTokenizer(
// this will read first line and separates values by (,) and stores them in tokens.
(String) reader.readLine(), ",");
tokens.nextToken(); // this method will read the tokens values on each call.
}
对于例如,CSV文件具有雇员的记录,如:
ram,101
tokens.nextToken()
致电将会返回ram
。tokens.nextToken()
致电将返回101
。读/ Java中操纵CSV,你可以检查出Apache POI库。
我建议https://commons.apache.org/proper/commons-csv/
“共享CSV读取和逗号分隔值(CSV)格式的变化写入文件。”
这项工作考虑到我正在使用我的电脑中使用的目录。但是,我想要的是文件上传,但'BufferedReader reader = new BufferedReader(new InputStreamReader(file));'似乎不工作,因为我在这一行发生错误'List items = new ServletFileUpload(new DiskFileItemFactory() ).parseRequest(request);' –
nubteens
对不起,我只是忘记导入一个jar文件。这完全有效!非常感谢你 – nubteens