【发布时间】:2015-01-31 14:44:50
【问题描述】:
我是安卓开发新手。目前,我正在开发一个简单的应用程序,用于将字符串数组写入和读取到内部存储。
首先我们有一个数组,然后将它们保存到存储中,然后下一个活动将加载它们并将它们分配给数组 B。谢谢
【问题讨论】:
-
即使您的活动已关闭,您也希望保存您的数组?
-
是的。像您从互联网下载然后保存然后下次只需从内部存储加载它
我是安卓开发新手。目前,我正在开发一个简单的应用程序,用于将字符串数组写入和读取到内部存储。
首先我们有一个数组,然后将它们保存到存储中,然后下一个活动将加载它们并将它们分配给数组 B。谢谢
【问题讨论】:
写入文件:
try {
File myFile = new File(Environment.getExternalStorageDirectory().getPath()+"/textfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.write("replace this with your string");
myOutWriter.close();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
从文件中读取:
String pathoffile;
String contents="";
File myFile = new File(Environment.getExternalStorageDirectory().getPath()+"/textfile.txt");
if(!myFile.exists())
return "";
try {
BufferedReader br = new BufferedReader(new FileReader(myFile));
int c;
while ((c = br.read()) != -1) {
contents=contents+(char)c;
}
}
catch (IOException e) {
//You'll need to add proper error handling here
return "";
}
因此,您将在字符串“contents”中取回文件内容
注意:您必须在清单文件中提供读写权限
【讨论】:
如果您希望将yourObject 存储到缓存目录,您可以这样做-
String[] yourObject = {"a","b"};
FileOutputStream stream = null;
/* you should declare private and final FILENAME_CITY */
stream = ctx.openFileOutput(YourActivity.this.getCacheDir()+YOUR_CACHE_FILE_NAME, Context.MODE_PRIVATE);
ObjectOutputStream dout = new ObjectOutputStream(stream);
dout.writeObject(yourObject);
dout.flush();
stream.getFD().sync();
stream.close();
再读一遍 -
String[] readBack = null;
FileInputStream stream = null;
/* you should declare private and final FILENAME_CITY */
inStream = ctx.openFileInput(YourActivity.this.getCacheDir()+YOUR_CACHE_FILE_NAME);
ObjectInputStream din = new ObjectInputStream(inStream );
readBack = (String[]) din.readObject(yourObject);
din.flush();
stream.close();
【讨论】:
【讨论】: