Store 2D array (String) to file and retrieve it

流过昼夜 提交于 2019-12-19 10:52:31

问题


I have made a simple program that has a 2D String array storing lots of data. I have searched a lot of places for how to store and retrieve 2D arrays. I want to save the data in my array at the end of the program and have this data retrieved upon the start of the program. I have tried: ObjectOutputStream toFile = new ObjectOutputStream(new FileWriter("array.DATA")); toFile.writeObject(array); This came up with the error: incompatible types: FileWriter cannot be converted to OutputStream

I only know basic programming so try to be easy on me and explain everything you say thoroughly. If I'm honest I don't even know what 'ObjectOutputStream' is.

Many thanks in advance


回答1:


In this example: This example is very simple(it's not a perfect solution but it's a good start to undestand how save and retrieve works).

Your 2d array is int a[][]= new int[12][12];

//or a is String a[][] = new String[12][12];

  • Part 1: (Save)

    public void Save(){
    
     try {
        PrintWriter writer = new PrintWriter(new File("C:/Users/Alex.hp/Desktop/t.txt"));
    
        for(int i=0; i<a.length; i++){
            for(int j=0; j<a[i].length; j++){
    
              //use this if your array has (int,double..)
                  // writer.write(String.valueOf(a[i][j])+" "); //Here you parse the int from array to String.
    
    
               //use this if your array has String
                 writer.write(a[i][j]+" "); //Its String so you dont have to use String.valueOf(something(int,double,...)
            }
           writer.println(); //leave one line 
        }
    
        writer.flush();  //flush the writer
        writer.close();  //close the writer      
    
    
    
       } catch (FileNotFoundException e) {      
         e.printStackTrace();
       }
    

    }//end of method

Using a simple PrintWriter you save your array into a file exaclty how it is. Just you know change the path i have put to the file;

  • Part 2: (Update or Retrieve on Open)

    public void UpdateOnOpen(){
    
     try {
        Scanner scan = new Scanner(new File("C:/Users/Alex.hp/Desktop/t.txt"));
    
    //Retrieve
            for(int i=0; i<a.length;  i++)
              for(int j=0; j<a[i].length; j++){
    
              //if you array use (int,double,...)
                //a[i][j]=Interger.parseInt(scan.next()) //for int
                //a[i][j]=Double.parseDouble(scan.next()) //for double
    
              //if your array use String
                a[i][j]=scan.next(); //Here you retrieve the array again from the file
    
    
              }//end of for(int j=0; j<a[i].length; j++)
    
    
    
         scan.close(); //close the resource file you opened
    
    //Print it to be sure all are right
              for(int i=0; i<a.length; i++){
                    for(int c=0; c<a[i].length; c++)
                          System.out.printf(""+a[i][c]+",");
    
                System.out.println();    
              }                         
    
      } catch (FileNotFoundException e){  e.printStackTrace(); }    
    
    
    }//end of method
    

    Using Scanner class you retrieve your array back from the file saved.

Also a better solution but you have to dig more here

Let me know it your job is done..




回答2:


There is an additional question to resolve, which is how do you store the sizes of the arrays as well as the contents. I would recommend using conversion to JSON. If you get the Jackson library, you should be able to use the Jackson Object Mapper. I would recommend storing your arrays within another object.

e.g.

class MyClass {
    String[][] myArray;

    // add the getters and setters to this class for myArray too
}

Then for storing

MyClass myObject = new MyClass();

// set the arrays here to whatever you like

ObjectMapper mapper = new ObjectMapper();
mapper.write(new File("c:\somedir\somefile.txt"), myObject);

Then for loading

ObjectMapper mapper = new ObjectMapper();
MyClass loaded = mapper.readValue(new File("c:\somedir\somefile.txt", MyClass.class);

// then you can use loaded as the source of your data



回答3:


You should be using FileOutputStream instead. FileWriter in character while ObjectOutputStream is binary output stream.

public static void main(String[] args) {
    try {
        ObjectOutputStream toFile = new ObjectOutputStream(new FileOutputStream("//home//user//array.DATA"));
        toFile.writeObject(args);
        toFile.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}


来源:https://stackoverflow.com/questions/28516417/store-2d-array-string-to-file-and-retrieve-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!