2

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.

Jake Graham Arnold
  • 1,331
  • 2
  • 18
  • 37
  • Is the `filename` you pass in to the `ReadByteFromFile(...)` method fully qualified? – Squonk Mar 01 '12 at 01:50
  • By fully qualified you mean the same? String filename = "BF.dat"; Both are the same. (I'll add this to my question) – Jake Graham Arnold Mar 01 '12 at 01:57
  • See dbryson's answer. You need to use `openFileInput` in your case. What I meant by fully qualified was something like `/data/data/.../.../BF.dat`. If you check your logcat you're probably getting a `FileNotFoundException` being logged with your code above. – Squonk Mar 01 '12 at 01:59
  • I cannot see the FileNotFoundException but what is there is that when i try to use the byte[] my logcat says: Casused by: java.lang.IllegalArgumentException: key is null.... key is equal to the return value so it is just returning null. – Jake Graham Arnold Mar 01 '12 at 02:07
  • I put in a deliberate wrong file name and same thing happens. So might be file name. I tried openFileInput(filename) as well but no luck, but maybe i am doing it wrong so i'll keep on trying – Jake Graham Arnold Mar 01 '12 at 02:11

1 Answers1

3

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)

dbryson
  • 5,477
  • 2
  • 18
  • 20