您的位置:首页 > 编程语言 > Java开发

java操作csv文件

2016-08-25 14:31 274 查看
public class CSVUtil {

/**
* 导出
*
* @param file csv文件(路径+文件名),csv文件不存在会自动创建
* @param dataList 数据
* @return
*/
public static boolean exportCsv(File file, List<String> 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 (String data : dataList) {
bw.append(data).append("\r");
}
}
isSucess = true;
} catch (Exception e) {
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;
}

/**
* 导入
*
* @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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: