簡體   English   中英

有關在Android中保存/訪問已保存文件的問題

[英]Questions about Saving/Accessing saved files in Android

好的,我在各種Android和場外文檔/幫助站點上閱讀了很多有關保存和訪問實現的內容,但是我仍然不了解該實現及其工作方式,因此,我的最后選擇是轉向StackOverFlow(我自己進行這項工作)

在這個問題上,我有時會聽起來有些愚蠢和遲鈍,因為我在編寫應用程序時正在動態學習,所以請耐心等待(我已經標注了整個文檔的一部分,問題):

首先,我看到要實現一個保存的文件,必須寫一個(取自android docs):

//Declarations
String FILENAME = "hello_file";
String string = "hello world!";

//Meaning that FILENAME is to be saved as hello_file, and "hello world!" converts the string to bytes
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

在將數據保存在其中的任何函數(例如按鈕)中,如下所示:

public void testButtonPressToSave() {

FileOutputStream testSaveFile = openFileOutput(SavedFile, Context.MODE_PRIVATE);
testSaveFile.write();
testSaveFile.close();

}

但是,當我將其實現為代碼時,Eclipse建議我在openFileOutput部分中使用try / catch異常,整個過程變為:

public void testButtonPressToSave() {
    FileOutputStream testSaveFile;
try {
    testSaveFile = openFileOutput(SavedFile, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
try {
    testSaveFile.write(testString.getBytes());
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
try {
    testSaveFile.close();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}

(問題)這正常嗎? 如果保存的文件在其他活動中,該如何重用? 我是否將整個主要活動導入到小部件提供程序類中?

另外,我完全理解:

1)  FileOutputStream testSaveFile; and testSaveFile = openFileOutput(SavedFile, Context.MODE_PRIVATE);

將testSaveFile聲明為FileOutputStream對象,並使用Context.MODE_PRIVATE來保存文件(.txt?),這將文件限制為只能由應用程序本身訪問。

和,

2)  testSaveFile.close(); 

以某種方式結束流(但這很直接,它只是關閉文件)

我真正不了解的部分是,如何在SavedFile數據包中保存多個變量?

Android文檔為我提供了FileOutputStream下的可用write()函數:

public void write (byte[] buffer, int offset, int byteCount)

public void write (byte[] buffer)

public void write (int oneByte)

這不是我想要的,因為我需要流來保存多個變量,例如String和Integer []。

(問題)如何將所需的數據類型保存到SavedFile中?

我也讀過有關序列化的信息,但是我不確定將文件保存到我的應用程序中如何工作。 另外,我不太相信在Dalvik VM(Android)上序列化會非常有效,因為我已閱讀和通過的大多數代碼都基於Java系統。

還有一個我不理解的Bundle android資源,但似乎是將各種多個變量存儲到一個包中,然后在下一個活動中將其解包的答案,盡管我看不到如何真正保存它放入文件或其他內容。

好吧,我在談論很多要點,但是如果有人能夠回答這些問題,我將不勝感激。 您不必提供答案,但是非常感謝您提供清晰的解釋(尤其是在技術術語:S周圍)

看來我已經找到了一種更有效的方法,可以通過Android中的SQLiteDatabase存儲數據。 不管怎么說,還是要謝謝你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM