我正在嘗試使用android.os.memoryfile寫入一個文件,然後從相同的文件中讀取。我用一種方法寫入文件並從另一種方法讀取,全部在同一個類中。我可以寫得很好,但是當我讀取文件時,我得到了符號的行,而不是我寫入文件的內容。看來,這個讀取方法並沒有讀取我寫過的文件。使用android.os.memoryfile的文件IO
如果我把代碼寫入和讀取文件的方法相同,它似乎工作正常。讀取文件輸出我寫的字符串。
這是我的代碼:
public class FileActivity extends Activity {
MemoryFile memFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
memFile = new MemoryFile("MemoryFileTest", 1000000);
} catch (IOException e) {
e.printStackTrace();
}
}
public void readFile() {
StringBuffer strBuffer = new StringBuffer();
try {
InputStream in = memFile.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String inputString;
while ((inputString = reader.readLine()) != null) {
strBuffer.append(inputString + "\n");
}
in.close();
reader.close();
Log.d(TAG, strBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeFile() {
String example = "This is an example";
byte[] bytes = example.getBytes();
try {
OutputStream out = memFile.getOutputStream();
out.write(bytes);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上面的代碼中,MemoryFile在類的頂部聲明,並且在onCreate()方法初始化。然後我試圖用這個MemoryFile編寫和閱讀。
我在這裏錯過了什麼?
+0
我通過調用'writeFile()'和'readFile()'在'onCreate()'的末尾添加了你的代碼。我在'logcat'輸出中看到了示例文本。示例文本的結尾是一串長長的符號,它們是黑色鑽石中的問號。你看到沒有文字輸出嗎?只是鑽石問號? –
+0
是的,我只看到帶有上述代碼的鑽石問號。如果我將寫入和讀取代碼放在一個方法中,我確實得到了原始字符串,沒有任何菱形問號。 –
+0
我的回答有用嗎? –