kilianvde
kilianvde

Reputation: 35

Android Studio - FileNotFound exception in editor

i'm getting this error in the android studio ide even before hitting "run".

Unhandled exception: java.io.FileNotFoundException

With this class:

(The function in the class is not yet being called!)

import java.io.*;


public class FileIO
{
public static byte[] readBinaryFileFromAssets(File file)
{
    byte[] data = null;

    DataInputStream dis = new DataInputStream(new FileInputStream(file));
    dis.readFully(data);
    dis.close();

    return data;
}
}

Thanks.

Upvotes: 0

Views: 1257

Answers (3)

René Boschma
René Boschma

Reputation: 28

You've got an exception which is not being caught. You need to add a try/catch block or let the method trow an exception.

    public static byte[] readBinaryFileFromAssets(File file){
    try{    
    byte[] data = null;

        DataInputStream dis = new DataInputStream(new FileInputStream(file));
        dis.readFully(data);
        dis.close();

        return data;
    }catch(FileNotFoundException e){
    //TODO something appropriate when the file isn't found
    }
return null;
    }

Upvotes: 0

PPartisan
PPartisan

Reputation: 8231

This looks like a checked exception. If you look at the Docs for the FileInputStream, you'll see it throws a FileNotFoundException.

Surround your code in a try/catch block to account for such an event and the error should go away. Something like:

try {
    DataInputStream dis = new DataInputStream(new FileInputStream(file));
    //etc...
} catch (FileNotFoundException e) {
    //Account for situations where the file can't be found
} 

Upvotes: 0

Bone
Bone

Reputation: 91

Its bothering you because you haven't handled a potential file not found exception. Surround it with try/catch or throw the exception.

 public static byte[] readBinaryFileFromAssets(File file)
    {
        byte[] data = null;

        DataInputStream dis = null;
        try {
            dis = new DataInputStream(new FileInputStream(file));
            dis.readFully(data);
            dis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return data;
    }

Note: you can automatically surround blocks in try/catch in android studio by doing alt+enter to bring up the options and then selecting "surround with try/catch"

Upvotes: 1

Related Questions