我是android開發新手。目前,我正在開發一個簡單的應用程序,用於將字符串數組寫入並讀取到內部存儲器。寫入/讀取字符串陣列到內部存儲器android
首先我們有一個數組,然後將其保存到存儲,那麼接下來的活動將加載它們,並將它們分配到陣列B.謝謝
我是android開發新手。目前,我正在開發一個簡單的應用程序,用於將字符串數組寫入並讀取到內部存儲器。寫入/讀取字符串陣列到內部存儲器android
首先我們有一個數組,然後將其保存到存儲,那麼接下來的活動將加載它們,並將它們分配到陣列B.謝謝
如果您想保存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();
要寫入文件:
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 "";
}
因此你會得到你的文件內容中的字符串「內容」
注意:您必須提供讀取和你的清單文件
寫權限
即使您的活動已關閉,您還希望保存數組嗎? – Darpan 2014-12-03 06:45:53
是的。像你一樣從互聯網下載然後保存它,然後下次從內部存儲裝載它 – 2014-12-03 06:47:32