我正在爲自己編寫一個簡單的預算應用程序,而且我很難弄清楚如何寫入內部存儲。我似乎沒有正確地寫入文件,並且我找不到更深入的示例,比Data Storage article on developer.android.com在閱讀和寫入內部存儲時遇到問題android
基本上,我試圖寫一個測試浮點到MyBalance文件,然後將其讀入餘額。在我的實際代碼中,我使用圍繞文件輸入/輸出操作的try/catch語句,但是我跳過它們以使代碼更具可讀性。
float test = 55;
float balance;
byte[] buffer = null;
FileOutputStream fos = openFileOutput("MyBalance", Context.MODE_PRIVATE);
fos.write(Float.floatToRawIntBits(balance));
fis.read(buffer); //null pointer
ByteBuffer b = ByteBuffer.wrap(buffer);
balance=b.getFloat();
這就是它的要義,任何人看到我做錯了什麼?
編輯: 感謝您的答覆,我繼續前進並轉換爲/從字符串像你建議的,但我仍然不認爲該文件正在創建。如果它存在於onResume()中並且它沒有運行,那麼我有一條if語句可以讀取它。 Lemme發佈了我的一些代碼。
以下是我正在寫的文件,(setbal是一個EditText和balanceview是一個TextView):
balance = Float.valueOf(setbal.getText().toString());
balanceview.setText(setbal.getText());
balstring = String.valueOf(balance);
for (int i = 0; i < balstring.length(); ++i)
try {
fos.write((byte)balstring.charAt(i));
} catch (IOException e) {
e.printStackTrace();
}
我檢查,如果該文件中的onResume()存在像這樣:
File file = new File("data/data/com.v1nsai.mibudget/balance.txt");
是否存儲該內容的內部文件?