62,614
社区成员
发帖
与我相关
我的任务
分享
import java.io.*;
public class Test{
private static double[][] value = new double[][] {
{ 5, 9, 2 },
{ 3, -4, 5 },
{ 2, 5, 1 },
{ -8, 3, 3 }
};
public static void write(String filepath)throws Exception{
OutputStream out=new FileOutputStream(filepath);
ObjectOutputStream oout=new ObjectOutputStream(out);
oout.writeObject(value);
}
public static double[][] read(String filepath)throws Exception{
InputStream in=new FileInputStream(filepath);
ObjectInputStream oin=new ObjectInputStream(in);
return (double[][])(oin.readObject());
}
public static void print(double[][] arr){
if(arr==null){
System.out.println("数组为空!");
return;
}
int row=arr.length;
int col=arr[0].length;
//System.out.println("row="+row+",col="+col);
System.out.println("{");
for(int i=0;i<row;i++){
System.out.print("{");
for(int j=0;j<col;j++){
System.out.print(arr[i][j]+" ");
}
System.out.print("}");
System.out.println();
}
System.out.println("}");
}
public static void main(String args[])throws Exception{
String filepath="d:\\1.txt";
write(filepath);
double[][] readResult=read(filepath);
print(readResult);
}
}
public class Test1 {
public static void main(String[] args) throws IOException {
double[][] value = new double[][] { { 5, 9, 2 }, { 3, -4, 5 },
{ 2, 5, 1 }, { -8, 3, 3,3 } };
File f = new File("d:/1.txt");
writeArray(value,f);
ArrayList<ArrayList<Double>> readArray = readArray(f);
System.out.println(readArray);
}
public static ArrayList<ArrayList<Double>> readArray(File f){
ArrayList<ArrayList<Double>> arrList=new ArrayList<ArrayList<Double>>();
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line="";
while((line = br.readLine())!=null){
String[] split = line.split(",");
ArrayList<Double> list=new ArrayList<Double>();
for(String str:split){
list.add(Double.parseDouble(str));
}
arrList.add(list);
}
br.close();
fr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return arrList;
}
public static void writeArray(double[][] arr,File file){
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (double[] v : arr) {
for (double d : v) {
bw.write(String.valueOf(d)+",");
}
bw.newLine();
}
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}