定义一个方法调用公共类的方法,实现将数据库中的数据存储成各种文件类型:很好的工具类
public void exportData(){
Ticket ticket = new Ticket();
//简单的时间格式转化
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = df.format(new Date());
SimpleDateFormat df1 = new SimpleDateFormat("yyyyMMdd");
//将时间转化为字符串
String dateString = df1.format(new Date());
//给对象设置值
ticket.setDateStr(dateStr);
//从数据库获取符合条件的值,返回List集合
List<Ticket> ticketList = mapper.getTicketList(ticket);
if(ticketList!=null && !ticketList.isEmpty()){
//获取Tomcat的bin目录(System.getProperty("user.dir")被调用时返回Tomcat的bin目录,否则返回当前工程所在的目录)
File pF = new File(System.getProperty("user.dir"));
//获取bin目录的上一级目录并新建文件夹tempfile用于存放导出的数据文件
String path = pF.getParent()+File.separator+"tempfile";
File file = new File(path);
if(!file.exists()){
file.mkdirs();
}
//给文件命名
String csvName = "0000192825_23"+dateString+"_01";
String fileUrl = path+File.separator+csvName+".csv";
//调用方法,实现数据的转化
boolean isSuccess = export.exportCsv(new File(fileUrl), ticketList);
System.out.println(isSuccess);
}
}
重新定义一个工具类:
定义一个公共类,用于将List集合存储为各种文件类型
package cmcc.gz.platform.hbqj.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import cmcc.gz.platform.hbqj.db.domain.Ticket;
/**
* Mysql 导出成CSV操作
*
* @author
* @version
*/
public class export {
/**
* 导出
*
* @param file csv文件(路径+文件名),csv文件不存在会自动创建
* @param dataList 数据
* @return
*/
public static boolean exportCsv(File file, List<Ticket> dataList){
boolean isSucess=false;
FileOutputStream out=null;
OutputStreamWriter osw=null;
BufferedWriter bw=null;
try {
out = new FileOutputStream(file);
osw = new OutputStreamWriter(out);
bw =new BufferedWriter(osw);
if(dataList!=null && !dataList.isEmpty()){
//通过for循环遍历集合,并按格式输出
for(Ticket t : dataList){
bw.append(t.getId()+","+t.getMobile()+","+t.getFee().intValue()).append("\r");
}
}
isSucess=true;
} catch (Exception e) {
e.printStackTrace();
isSucess=false;
}finally{
if(bw!=null){
try {
bw.close();
bw=null;
} catch (IOException e) {
e.printStackTrace();
}
}
if(osw!=null){
try {
osw.close();
osw=null;
} catch (IOException e) {
e.printStackTrace();
}
}
if(out!=null){
try {
out.close();
out=null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
return isSucess;
}
}