The problem with reading and writing to internal memory

I am writing a simple budget application for myself, and it is difficult for me to understand how to write on the internal storage. It seems that I am not writing to the file correctly, and I cannot find more detailed examples than the "Data Warehouse" developer.android.com

Basically, I am trying to write a test float to a MyBalance file, and then read it into balance. In my actual code, I use try / catch statements around file I / O, but I skipped them to make the code more readable.

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();

To judge this, does anyone see what I'm doing wrong?

Edit: Thanks for the answer, I went ahead and converted to / from String as you suggested, but I still don't think the file is being created. I have an if statement that reads it if it exists in onResume () and it does not start. Lemme will post some of my code.

This is how I write the file (setbal is EditText and balanceview is 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();
     }

I check if the file exists in onResume () as follows:

File file = new File("data/data/com.v1nsai.mibudget/balance.txt");

This is where the internal file is stored for this context?

+3
source share
1 answer

So, this is not exactly what you asked for, but this is how I work on Strings, and it might be useful for you to look. (You can insert primitives and toString them, of course, if you want to use this code.)

Record

FileOutputStream fos = context.openFileOutput("savedstate.txt", 0);

for (int i = 0; i < out.length(); ++i)
    fos.write((byte)out.charAt(i));

Reading

StringBuilder inb = new StringBuilder();

FileInputStream fis = this.mContext.openFileInput("savedstate.txt");

int ch;
while((ch = fis.read()) != -1)
    inb.append((char)ch);

Update

, , , , File, . FileInputStream , , , - , , .

, , , DDMS.

, try/catch . , , try/catch.

, , , File , , :

File file = new File("/data/data/com.v1nsai.mibudget/balance.txt");

.

+5

Source: https://habr.com/ru/post/1751937/


All Articles