android.os文件,使用android.os.memoryfile的文件IO

我正在嘗試使用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

我的回答有用嗎? –

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值