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; /**
* CSV操作(导出和导入)
*
*/
public class CSVUtil { /**
* 导出
*
* @param file
* csv文件(路径+文件名),csv文件不存在会自动创建
* @param dataList
* 数据
* @return
*/
public static String exportCsv(File file, List<String> dataList) { boolean isSucess = false; if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
} FileOutputStream out = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try {
out = new FileOutputStream(file);
osw = new OutputStreamWriter(out, "UTF-8");
bw = new BufferedWriter(osw);
if (dataList != null && !dataList.isEmpty()) {
for (String data : dataList) {
bw.append(data).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 file.getAbsolutePath();
} /**
* 导入
*
* @param file
* csv文件(路径+文件)
* @return
*/
public static List<String> importCsv(File file) {
List<String> dataList = new ArrayList<String>(); BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String line = "";
while ((line = br.readLine()) != null) {
dataList.add(line);
}
} catch (Exception e) {
} finally {
if (br != null) {
try {
br.close();
br = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
return dataList;
} public static void main(String[] args) {
// File file = new File("D:/s.csv");
// CSVUtil.importCsv(file); File file = new File("D:/222.csv");
List<String> dataList = new ArrayList<String>();
dataList.add("1");
dataList.add("2");
dataList.add("3");
dataList.add("4");
dataList.add("5"); CSVUtil.exportCsv(file, dataList); } }