Java中怎样将一个文件中的数据读取出来,并保存成数组。

我有一个名为data.txt的文件,文件内容为
0 0 0 0 0 0 0 1 0 0
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
现想将这个文件中的内容读出,并保存成一个二维数组的形式,应该怎样做?
如果想将数组再以文件的形式输出,又该怎样做?如果事先不知道数据文件的行数和列数时怎么办?可以将数组保存成ArrayList形式的吗?

第1个回答  2008-02-20
首先,按行读取数据,保存在StringBuffer里,然后转成数组

。。来不及了,我们要做班车,明天写给你
第2个回答  推荐于2016-04-26
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class Data2Array {
public static void main(String[] args) {
Data2Array test = new Data2Array();
String[][] array = test.parse();

for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
System.out.println(array[i][j]);
}
}
}

private String[][] parse() {
String[][] result = new String[10][10];
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream("data.txt")));

int cnt = 0;
String line;
while (null != (line = br.readLine())) {
result[cnt] = parseLine(line);
cnt++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}

private String[] parseLine(String line) {
String[] nums = line.split(" ");
return nums;
}
}本回答被提问者采纳
第3个回答  2008-02-20
public class Test{

public void readFile(String destFile, int[][] value) {
File in = new File(destFile);
try {
String tmp = "";
int line = 0;
logger.info("reading from file start:" + destFile);
BufferedReader br = new BufferedReader(new FileReader(in));
while ((tmp = br.readLine()) != null) { // user flag line
String tmps[] = tmp.split(" ");
for (int i = 0; i < tmps.length; i++) {
value[line][i] = Integer.parseInt(tmps[i].trim());
}
tmps = null;
line++;
}
br.close();
logger.info("end of reading file:" + destFile);
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args){
Test t =new Test();
int[][] tmp = new int[10][10];
t.readFile("data.txt",tmp);
for(int i=0;i<tmp.length;i++){
for(int j=0;j<tmp[0].length;j++){
System.out.print(tmp[i][j]+" ");
}
System.out.println();
}
}
}