我制作了一个简单的程序,其中有一个存储大量数据的 2D 字符串数组。我搜索了很多地方来了解如何存储和检索二维数组。我想在程序结束时将数据保存在数组中,并在程序启动时检索该数据。我努力了:ObjectOutputStream toFile = new ObjectOutputStream(new FileWriter("array.DATA"));
toFile.writeObject(array);
这出现了错误:不兼容的类型:FileWriter无法转换为OutputStream
我只知道基本的编程,所以尽量对我轻松一点,并彻底解释你所说的一切。老实说,我什至不知道“ObjectOutputStream”是什么。
提前谢谢了
在这个例子中:
这个例子非常简单(这不是一个完美的解决方案,但它是了解保存和检索如何工作的良好开端).
你的二维数组是 int a[][]= 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<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();
}
}//方法结束
使用简单的 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<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
使用 Scanner 类,您可以从保存的文件中检索数组。
也是一个更好的解决方案,但你必须挖掘更多here
让我知道你的工作已经完成了..
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)