二维数组保存函数 void save (double[][] array, int row, int column, string filename)
要求输入参数为需要保存的二维数组,数组的行数,数组的列数,以及保存的目标文件名
然后把数组保存到一个文本文件中
保存前先清空该文件
文件的第一行为行数和列数 (这主要是为了方便下面的二维数组读取函数处理)
后面几行分别为二维数组的内容二维数组读取函数 double[][] read(string filename)
要求输入参数为需要读取的文件名
然后从该文件中读取由前一个二维数组保存函数产生的文件,并将读取后的内容返回为一个二维数组
基本设想是这样的,请问怎么写呀~
谢谢~

解决方案 »

  1.   

    自己按要求再改改吧,没考虑行列数目不同的情况import java.io.*;public class ArraysReadWrite{

    private void save (double[][] array, int row, int column, String filename){
    File tFile = new File(filename);
    if(tFile.exists()){
    tFile.delete();
    }
    BufferedWriter bw = null;
    OutputStreamWriter osw = null;
    FileOutputStream fos = null;
    try{
    tFile.createNewFile();
    fos = new FileOutputStream(tFile);
    osw = new OutputStreamWriter(fos);
    bw = new BufferedWriter(osw); 
    bw.write(row+",");
    bw.write(column+"\n");
    StringBuilder sb = null;
    for(int i = 0 ;i < row ; i ++){
    sb = new StringBuilder();
    for(int j = 0 ; j < column -1; j ++){
    sb.append(array[i][j]+",");
    }
    sb.append(array[i][column-1]+"\n");
    bw.write(sb.toString());
    bw.flush();
    }
    }catch(FileNotFoundException e){
    e.printStackTrace();
    }catch(IOException e){
    e.printStackTrace();
    }finally{
    try{
    if(bw != null)
    bw.close();
    }catch(IOException e){
    e.printStackTrace();
    }
    }
    }

    private double[][] read(String filename) {
    double[][] result = null;
    BufferedReader br = null;
    InputStreamReader isr = null;
    File file = new File(filename);
    if(!file.exists())
    return result;
    String lineStr = null;
    String[] temp = null;
    try{
    isr = new FileReader(file);
    br = new BufferedReader(isr);
    lineStr = br.readLine();
    if(lineStr != null){
    temp = lineStr.split(",");
    result = new double[Integer.valueOf(temp[0])][Integer.valueOf(temp[1])];
    }
    int row = 0;
    int column = 0;
    while((lineStr = br.readLine()) != null){
    column = 0;
    temp = lineStr.split(",");
    for(int i = 0 ; i< temp.length ; i ++){
    result[row][column++] = Double.valueOf(temp[i]);
    }
    row ++;
    }
    }catch(Exception e){
    e.printStackTrace();
    }finally{
    if(br != null) try{
    br.close();
    }catch(IOException e){
    e.printStackTrace();
    }
    }
    return result;
    }
    public static void main(String[] args) throws Exception {
    ArraysReadWrite arw = new ArraysReadWrite();
    double[][] dArray = {{1,2},{2,3},{4,5},{6.5,5.5}};
    String filePath = "d:/temp.txt";
    arw.save(dArray,4,2,filePath);
    double[][] result = arw.read(filePath);
    System.out.println();
    }
    }