为了明天的建模比赛,紧急测试了一下java读取写入文件的能力。主要是为了防止去年文件太大,MATLAB读取慢的问题。同时祝愿今年可以取得好成绩!
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.junit.Test;
public class Readdat {
@SuppressWarnings("resource")
@Test
public void datTest() throws IOException {
File file = new File("C:\genotype.dat");
BufferedReader br = null;
List<String[]> list = new ArrayList<>();
br = new BufferedReader(new FileReader(file));
String content = null;
int i = 1;
while (true) {
content = br.readLine();
if (content == null) {
break;
}
String[] ss = content.split(" ");
// System.out.println(content);
System.out.println(i++);
list.add(ss);
}
System.out.println("done");
}
@SuppressWarnings("resource")
@Test
public void datfastTest() throws IOException {
File file = new File("C:\genotype.dat");
Scanner s = new Scanner(file);
List<String[]> list = new ArrayList<>();
int j = 1;
int i = 0;
String[] ss = new String[9445];
while (s.hasNext()) {
ss[i] = s.next();
if (i++ == 9444) {
i = 0;
list.add(ss);
ss = new String[9445];
System.out.println(j++);
}
}
System.out.println("done");
//存入文件
File newfile = new File("D:/newfile.dat");
FileWriter fw = null;
BufferedWriter writer = null;
fw = new FileWriter(newfile);
writer = new BufferedWriter(fw);
for (int k = 0; k < list.size(); k++) {
for (int kk = 0; kk < 9445; kk++) {
writer.write(list.get(k)[kk].toString() + " ");
}
writer.newLine();
}
writer.flush();
writer.close();
fw.close();
}
}