同样以CSV为例总结一下文件下载
1.下载内容做成
(1)下载内容的集合做成
List<List<String>> downloadList = new ArrayList<List<String>>();
(2)下载内容中每条记录做成(以下载表结构文件为例)
List<String> rowHeadList = new ArrayList<String>();//表头制作
rowHeadList.add("ID");
rowHeadList.add("NAME");
rowHeadList.add("AGE");
rowHeadList.add("SEX");
rowHeadList.add("BIR");
List<String> rowDataList = new ArrayList<String>();
rowDataList.add("1");
rowDataList.add("张三");
rowDataList.add("18");
rowDataList.add("男");
rowDataList.add("1999/09/09");
downloadList .add(rowHeadList );//将表头内容添加到下载内容中
downloadList .add(rowDataList );//将记录数据添加到下载内容中
3.设定文件保存目录
String fileSavePath = "C:/Desktop/download/";
File folder= new File(fileSavePath );//创建文件保存目录
//文件保存目录不存在的情况下创建
if (!folder.exists()) {
folder.mkdir();
}
4.下载文件名及格式,路径定义
String fileUserInfo = folder+ "用户信息表" + ".csv";
5.开始文件下载
writeCsvFile(downloadList , fileUserInfo );
public void writeCsvFile(List<List<String>> downloadList , String fileUserInfo ) {
try {
BufferedWriter bfWriter =
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), ENCODING_UTF8));//下载文件文字格式确定
// 下载内容保存
for (List<String> row : downloadList ) {
bfWriter.write(""");
bfWriter.write(String.join("","", row));
bfWriter.write(""");
bfWriter.newLine();//换行
}
bfWriter.flush();//清除缓存
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
if (bfWriter != null) {
bfWriter.close();//关闭并保存文件
}
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
}