将2D数组(String)存储到文件并检索它

我做了一个简单的程序,它有一个存储大量数据的2D String数组。 我搜索了很多地方,了解如何存储和检索2D数组。 我想在程序结束时将数据保存在我的数组中,并在程序启动时检索这些数据。 我试过: ObjectOutputStream toFile = new ObjectOutputStream(new FileWriter("array.DATA")); toFile.writeObject(array); ObjectOutputStream toFile = new ObjectOutputStream(new FileWriter("array.DATA")); toFile.writeObject(array); 这就产生了错误:不兼容的类型:FileWriter无法转换为OutputStream

我只知道基本的编程,所以试着对我很轻松并解释你所说的一切。 如果我老实说我甚至都不知道’ObjectOutputStream’是什么。

提前谢谢了

还有一个问题需要解决,即如何存储数组的大小以及内容。 我建议使用转换为JSON。 如果您获得Jackson库,您应该能够使用Jackson Object Mapper。 我建议将数组存储在另一个对象中。

例如

 class MyClass { String[][] myArray; // add the getters and setters to this class for myArray too } 

然后存储

 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); 

然后加载

 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 

在这个例子中:这个例子非常简单( 它不是一个完美的解决方案,但它是一个很好的开始,可以解决保存和检索的工作原理 )。

你的2d数组是int [] [] = new int [12] [12];

//或a是String a [] [] = new String [12] [12];

  • 第1部分:(保存)

     public void Save(){ try { PrintWriter writer = new PrintWriter(new File("C:/Users/Alex.hp/Desktop/t.txt")); for(int i=0; i 

    } //方法结束

使用简单的PrintWriter,您可以将数组保存到文件中,不管它是多少。 只是你知道改变我放到文件的路径;

  • 第2部分:(更新或检索打开)

     public void UpdateOnOpen(){ try { Scanner scan = new Scanner(new File("C:/Users/Alex.hp/Desktop/t.txt")); //Retrieve for(int i=0; i 

    使用Scanner类可以从保存的文件中检索数组。

也是一个更好的解决方案,但你必须在这里挖掘更多

让我知道你的工作已经完成..

您应该使用FileOutputStream。 FileWriter的字符,而ObjectOutputStream是二进制输出流。

 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(); } }