java生成txt文檔,指定編碼格式
/**
* 寫入txt檔案
*
* @param result
* @param fileName
* @return
*/
public static boolean writeDataHubData(List<String> result, String fileName) {
long start = System.currentTimeMillis();
String filePath = "D:\\export\\txt";
StringBuffer content = new StringBuffer();
boolean flag = false;
BufferedWriter out = null;
try {
if (result != null && !result.isEmpty() && StringUtils.isNotEmpty(fileName)) {
fileName += "_" + System.currentTimeMillis() + ".txt";
File pathFile = new File(filePath);
if(!pathFile.exists()){
pathFile.mkdirs();
}
String relFilePath = filePath + File.separator + fileName;
File file = new File(relFilePath);
if (!file.exists()) {
file.createNewFile();
}
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "GBK"));
// //标題頭
// out.write("curr_time,link_id,travel_time,speed,reliabilitycode,link_len,adcode,time_stamp,state,public_rec_time,ds");
// out.newLine();
for (String info : result) {
out.write(info);
out.newLine();
}
flag = true;
logger.info("寫入檔案耗時:*********************************" + (System.currentTimeMillis() - start) + "毫秒");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return flag;
}
}