java读写CSV文件

java读写CSV文件

觉得有用的话,欢迎一起讨论相互学习~Follow Me

参考文献
读取csv文件中数据
将数据保存为csv文件格式

读取CSV文件中的数据

import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;


public class readCSV {
    void readCSV(String readpath, ArrayList Nolist, ArrayList Dnalist) {
        File inFile = new File(readpath);
        try {
            BufferedReader reader = new BufferedReader(new FileReader(inFile));
            while (reader.ready()) {
                String line = reader.readLine();
                StringTokenizer st = new StringTokenizer(line, ",");
                int NO;
                String DNAsequence;

                if (st.hasMoreTokens()) {
                    NO = Integer.valueOf(st.nextToken().trim());
                    DNAsequence = String.valueOf(st.nextToken().trim());
                    Nolist.add(NO);
                    Dnalist.add(DNAsequence);
                }
            }
            reader.close();

        } catch (Exception e) {

            e.printStackTrace();
        }
    }
}

将数据保存为csv格式

package Readcsv_testV0;


import java.io.*;
import java.util.ArrayList;

public class OutputCSV {
    public static void writeCSV(ArrayList<String []> DNA, ArrayList<Double> Con, ArrayList<Double> Hp, ArrayList<Double> Hm, ArrayList<Double> Si, ArrayList<Double> Tm, ArrayList<Double> GC, String path) {
        try {
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), "UTF-8"));
            for (int i = 0; i < DNA.size(); i++) {
                out.write(DNA.get(i)[0]);
                out.write(",");
                out.write(DNA.get(i)[1]);
                out.write(",");
                out.write(Con.get(i).toString());
                out.write(",");
                out.write(Hp.get(i).toString());
                out.write(",");
                out.write(Hm.get(i).toString());
                out.write(",");
                out.write(Si.get(i).toString());
                out.write(",");
                out.write(Tm.get(i).toString());
                out.write(",");
                out.write(GC.get(i).toString());
                out.newLine();
            }
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

猜你喜欢

转载自www.cnblogs.com/cloud-ken/p/11093594.html