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.

5
  • Is the filename you pass in to the ReadByteFromFile(...) method fully qualified? Commented Mar 1, 2012 at 1:50
  • By fully qualified you mean the same? String filename = "BF.dat"; Both are the same. (I'll add this to my question) Commented Mar 1, 2012 at 1: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. Commented Mar 1, 2012 at 1: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. Commented Mar 1, 2012 at 2: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 Commented Mar 1, 2012 at 2:11

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.