write CSV file - Java File Path IO

Java examples for File Path IO:CSV File

Description

write CSV file

Demo Code


//package com.java2s;

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;
        BufferedWriter bw = null;

        try {//  w ww  .  jav  a  2s  .  c om
            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();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
            }
            try {
                osw.close();
            } catch (IOException e) {
            }
            try {
                bw.close();
            } catch (IOException e) {
            }
        }
    }
}

Related Tutorials