集册 Java实例教程 写入CSV文件

写入CSV文件

欢马劈雪     最近更新时间:2020-01-02 10:19:05

516
写入CSV文件
/**来 自 N o w J a v a . c o m - 时  代  Java**/

//package com.nowjava;


import java.io.BufferedWriter;

import java.io.File;


import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;


import java.io.OutputStreamWriter;

import java.io.UnsupportedEncodingException;


import java.util.List;


public class Main {

    public static void write(List<List<String>> list, String fileName,

            String charsetName) {

        File outFile = new File(fileName);


        FileOutputStream fos = null;

        OutputStreamWriter osw = null;//n o w j a   v  a . c o m - 时  代  Java 提供

        BufferedWriter bw = null;


        try {

            fos = new FileOutputStream(outFile);

            osw = new OutputStreamWriter(fos, charsetName);

            bw = new BufferedWriter(osw);

            for (int j = 0; j < list.size(); j++) {

                List<String> rowList = list.get(j);

                for (int i = 0; i < rowList.size(); i++) {

                    String str = rowList.get(i);

                    bw.write("\"");

                    bw.write(str);

                    bw.write("\"");


                    if (i < rowList.size() - 1) {

                        bw.write(",");

                    }

                }

                if (j < list.size() - 1) {

                    bw.write("\n");

                }

            }

            bw.flush();

            System.out.println(String.format("???%s?", list.size()));

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        } 
展开阅读全文