案例代码:
import java.io.*;
import java.util.*;
public class SaveAndReadArrayByWriter {
public static void save(int[][] datas)throws
IOException{
PrintWriter pw=new PrintWriter("array.txt");
pw.println(datas.length);
pw.println(datas[0].length);
String content="";
for(int i=0;i<datas.length;i++){
for(int j=0;j<datas[0].length;j++){
if(j<datas[0].length-1) {
content+=datas[i][i]+",";
}else{
content+=datas[i][i]+"\n";
}
}
}
pw.print(content);
pw.close();
}
public static void read()throws IOException{
BufferedReader reader=new BufferedReader(new FileReader("array.txt"));
String strRow=reader.readLine();
int row=Integer.parseInt(strRow);
String strCol=reader.readLine();
int col=Integer.parseInt(strCol);
int[][]datas=new int[row][col];
String content="";
for(int i = 0; i < datas.length; i++) {
content = reader.readLine();
if(content == null)break;
String[]strDatas = content.split(",");
for(int j = 0; j < datas[0].length; j++) {
datas[i][j] = Integer.parseInt(strDatas[j]);
}
}
System.out.println(Arrays.deepToString(datas));
reader.close();
}
public static void main(String[] args)throws
IOException{
int[][]a={{1,2,3},{4,5,6},{7,8,9}};
save(a);
read();
}
}
案例运行图: