Java导出CSV文件

来源:互联网 发布:网络巡更系统 编辑:程序博客网 时间:2024/04/28 00:27

//获得U盘名称public static String getUDiskName () {String diskName = null;//获得文件系统网关FileSystemView sys = FileSystemView.getFileSystemView();File[] files = File.listRoots();for (int i = 0; i < files.length; i++) {//获取文件系统类型String sysTypeDesc = sys.getSystemTypeDescription(files[i]);if (null != sysTypeDesc && "可移动磁盘".equals(sysTypeDesc)) {diskName = files[i].toString();break;}}return diskName;}

//导出CSV文件

public static void exportCSV (File file, List<String[]> dataList) {FileOutputStream out = null;OutputStreamWriter osw = null;BufferedWriter bw = null;//缓冲流try {out = new FileOutputStream(file);osw = new OutputStreamWriter(out, "GBK");bw = new BufferedWriter(osw);if (dataList != null && !dataList.isEmpty()) {for (String[] strs : dataList) {for (String str : strs) {bw.append(str).append(","); //用Excel打开时相当于是切换到下一个单元格}bw.append("\n"); //用Excel打开时相当于是切换到下一个行}}bw.flush();} catch (Exception e) {e.printStackTrace();} finally {try {if (bw != null) {bw.close();}if (osw != null) {osw.close();}if (out != null) {out.close();}} catch (IOException e) {e.printStackTrace();}}}
//导入
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;    }


原创粉丝点击