package com.test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
public class Export {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Hello,World!");
list.add("Hello,World!");
list.add("Hello,World!");
list.add("Hello,World!");
File file = new File("D:/123.txt");
if(!file.exists()){
file.mkdir();
}
boolean isSuccess=exportTxt(file, list);
System.out.println(isSuccess);
}
/**
* 導出
*
* @param file
* Txt檔案(路徑+檔案名),Txt檔案不存在會自動建立
* @param dataList
* 資料
* @return
*/
public static boolean exportTxt(File file, List<String> dataList) {
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
return exportTxtByOS(out, dataList);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
}
/**
* 導出
*
* @param out
* 輸出流
* @param dataList
* 資料
* @return
*/
public static boolean exportTxtByOS(OutputStream out, List<String> dataList) {
boolean isSucess = false;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try {
osw = new OutputStreamWriter(out);
bw = new BufferedWriter(osw);
// 循環資料
for (int i = 0; i < dataList.size(); i++) {
bw.append(dataList.get(i)).append("\r\n");
}
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;
}
}