java JSP/Servlets:如何上传 zip 文件、解压并提取 CSV 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3768104/
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
JSP/Servlets: How do I Upload a zip file, unzip it and extract the CSV file
提问by Roy
Wondering how can I do the following in JSP/Servlets:
想知道如何在 JSP/Servlets 中执行以下操作:
Upload a zip file (containing multiple CSV files)
Unzip the file to obtian the CSV files
Read the CSV files and pump the records into a mySQL database
上传一个 zip 文件(包含多个 CSV 文件)
解压缩文件以获取 CSV 文件
读取 CSV 文件并将记录泵入 mySQL 数据库
Note: mySQL table is set up and ready for CSV files inputs.
注意:mySQL 表已设置并准备好用于 CSV 文件输入。
Thanks in advance.
提前致谢。
回答by BalusC
1: Upload a zip file (containing multiple CSV files)
1:上传一个zip文件(包含多个CSV文件)
Use a multipart/form-data
form with input type="file"
in HTML/JSP to be able to select a file and upload it. Use Apache Commons FileUploadin the Servlet to be able to parse the request body and obtain the uploaded files. See also: How to upload files in JSP/Servlet?
使用HTML/JSP 中的multipart/form-data
表单input type="file"
可以选择文件并上传。在 Servlet 中使用Apache Commons FileUpload可以解析请求体并获取上传的文件。另请参阅:如何在 JSP/Servlet 中上传文件?
2: Unzip the file to obtian the CSV files
2: 解压文件以获取 CSV 文件
Use java.util.ZipInputStream
to read a zip file and extract the zip entries. See also: Compressing and Decompressing files in Java.
使用java.util.ZipInputStream
读取压缩文件并解压ZIP条目。另请参阅:在 Java 中压缩和解压缩文件。
3: Read the CSV files and pump the records into a mySQL database
3:读取 CSV 文件并将记录泵入 mySQL 数据库
Two ways:
两种方式:
Put the CSV somewhere on the local disk file system where the MySQL has access to and instruct it to import it using a
LOAD DATA INFILE
query.Use an existing CSV parseror create oneto parse a CSV into a useable collection of Java objects, e.g.
List<List<String>>
. Then learn JDBCand usePreparedStatement
to create, populate and execute anINSERT
query in batches. See also this mini tutorial on MySQL and JDBC.
将 CSV 放在 MySQL 可以访问的本地磁盘文件系统上的某个位置,并指示它使用
LOAD DATA INFILE
查询导入它。使用现有的CSV 解析器或创建一个解析器将 CSV 解析为可用的 Java 对象集合,例如
List<List<String>>
. 然后学习 JDBC并使用它PreparedStatement
来INSERT
批量创建、填充和执行查询。另请参阅有关 MySQL 和 JDBC 的此迷你教程。