Search code examples
javaandroidwritetofile

Read/Write Byte array Android


Trying to write a byte[] to a file, which i think is working correctly

   String filename = "BF.dat";



   public void WriteByteToFile(byte[] mybytes, String filename){

    try {

    FileOutputStream FOS = openFileOutput(filename, MODE_PRIVATE);
    FOS.write(mybytes);
    FOS.close();


    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Then later in the app I need to read the bytes back into a byte[]

       String filename = "BF.dat"

   public byte[] ReadByteFromFile (String filename){

    byte[] mybytes = null;

    try {
        File file = new File(filename);     
        FileInputStream FIS = new FileInputStream(file);

        mybytes = new byte[(int)file.length()];

            FIS.read(mybytes);  
            FIS.close();



    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return mybytes;
}   

The bytes are not being returned from this, (it works in normal java - but not with the android apk) I'm not sure what I need to make it work in android. There are lots of example of writing bytes to files but I can't find any that explain how to get them back.

If anything is to vague please comment and I will explain more if required.


Solution

  • Could it be that you're writing the file to the context's private storage but not reading it back from there? Try reading the file with openFileInput(filename)