java读取写入CSV文件
觉得有用的话,欢迎一起讨论相互学习~
读取CSV文件中的数据示例一
public void test() {
readValues(OutputfilePath, Valueslist);
for (int i = 0; i < Valueslist.size(); i++) {
for (int j = 0; j <Valueslist.get(0).length; j++) {
System.out.print(Valueslist.get(i)[j]+" ");
}
System.out.println();
}
}
public void readValues(String readpath, ArrayList<Double[]> Valueslist) {
//想要读取的数据是一个[N,Dim]的二维矩阵
File inFile = new File(readpath);
try {
BufferedReader reader = new BufferedReader(new FileReader(inFile));
while (reader.ready()) {
//这里没有办法使用矩阵进行操作,因为我们一行一行的读没有办法知道csv中保存数据的长度和宽度
//但是返回的是一个String,我们可以对这个String进行操作,按照分隔符将其分割,最好能是能够保存到一个完整的结构中
String line = reader.readLine();
String[] splitline = line.split(",");
//这里每一列的元素都是一个double数值,例如
//因此接下来我能够直接的转换成Double类型的变量
int Dim = splitline.length;
//将splitline中的每个元素保存到double类型的数组中
Double[] temp = new Double[Dim];
for (int i = 0; i < Dim; i++) {
temp[i] = Double.valueOf(splitline[i]);
}
Valueslist.add(temp);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
读取CSV文件中的数据示例二
- 示例二维读取一个N行两列的逗号分隔的二维数字字符串混合的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());
//使用ArrayList接收数据
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();
}
}
}