[英]How save a string to a file in Android to be able to read it later?
我正在嘗試實施http://developer.android.com/guide/topics/data/data-storage.html中的 “使用內部存儲”部分
我認為我正確地完成了第一部分,將字符串保存到文件中,但是以后如何讀取字符串呢?
她就是我的代碼:
String FILEPROFILE = "profileinfo";
FileOutputStream fos = null;
BufferedInputStream fis = null;
OutputStream out = null;
try {
fos = openFileOutput(FILEPROFILE, Context.MODE_PRIVATE);
fos.write(profile.toString().getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis = new BufferedInputStream(new FileInputStream(FILEPROFILE));
Log.d("UsersThoughts", "BufferedInputStream is " + fis.read());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
編輯:我將其更改為此:
try {
fis = openFileInput(FILEPROFILE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Log.d("UsersThoughts", "This blah object read " + fis.read());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("UsersThoughts", "This blah object trying to read: " + e.toString());
}
try{
Log.d("UsersThoughts", "This blah object toString " + fis.toString());
} catch (Exception e)
{
e.printStackTrace();
Log.e("UsersThoughts", "This blah object trying to make string: " + e.toString());
}
logcat中的輸出如下所示:
11-15 18:41:34.862: D/UsersThoughts(7777): This blah object read123
11-15 18:41:34.862: D/UsersThoughts(7777): This blah object toString java.io.FileInputStream@46356128
看起來好像是在咬文件。...我如何找回復制的文本?
我引用的是您引用的相同來源:
要從內部存儲讀取文件:
調用openFileInput()並將其傳遞給要讀取的文件名。 這將返回FileInputStream。
使用read()從文件讀取字節。
然后使用close()關閉流。
編輯:例如,
FileInputStream fis = openFileInput("FILENAME");
BufferedInputStream blah = new BufferedInputStream(fis);
然后做任何你較早前在這方面采取blah
對象。
按照我在此處給出的答案將字符串存儲到Android中的文件: 如果用戶離線,是否應該在sqlite中存儲數據?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.