[英]Write/Read arrays in files android
for now i´ve got this two arrays that i want to save in a file 现在,我有两个要保存在文件中的数组
int var[][] = new int var[6][3]
int var_2[][] = new int var[7][5];
So whats the best way to write this into a file? 那么将其写入文件的最佳方法是什么?
I´ve seen some examples like this 我看过这样的例子
try {
ObjectOutputStream objOut = new ObjectOutputStream(new
FileOutputStream("data.dat"));
objOut.writeObject(var_1);
objOut.writeObject(var_2);
objOut.close();
}
catch (Exception e) {
e.printStackTrace();
}
Am i doing this right? 我说的对吗? And if i am, how then do i read it right to my variables?
如果是的话,我该如何正确读取变量?
You're doing it right in concept, but there's room for improvement. 您在概念上做得正确,但仍有改进的空间。 First, you should use the Android logging facility (
android.util.Log
) rather than e.printStackTrace()
. 首先,您应该使用Android日志记录工具(
android.util.Log
)而不是e.printStackTrace()
。 Also, if your minSdkLevel is 19 or more, I recommend that you use the try-with-resources statement: 另外,如果您的minSdkLevel为19或更高,我建议您使用try-with-resources语句:
try (ObjectOutputStream objOut = new ObjectOutputStream(new
FileOutputStream("data.dat")))
{
objOut.writeObject(var_1);
objOut.writeObject(var_2);
} catch (Exception e) {
Log.e(LOG_TAG, "Could not save data", e);
}
( LOG_TAG
is just some String
you define to identify your class's output.) If you can't use try-with-resources, I recommend using a finally
clause to close the stream: (
LOG_TAG
只是您定义的一些String
,用于标识类的输出。)如果不能使用try-with-resources,则建议使用finally
子句关闭流:
ObjectOutputStream objOut = null;
try {
objOut = new ObjectOutputStream(new FileOutputStream("data.dat"))
objOut.writeObject(var_1);
objOut.writeObject(var_2);
} catch (Exception e) {
Log.e(LOG_TAG, "Could not save data", e);
} finally {
if (objOut != null) {
try {
objOut.close();
} catch (Exception e) {
Log.e(LOG_TAG, "Could not close output file", e);
}
}
}
This ensures that the output stream gets closed even if an exception is thrown in the calls to writeObject
. 这样可以确保即使在
writeObject
的调用中引发异常时,输出流也可以关闭。
To read the data back in, just open an ObjectInputStream
to the same file and read the data in the same order in which you wrote them . 要读回数据,只需打开一个
ObjectInputStream
到相同的文件,并按照编写它们的相同顺序读取数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.