Android – FileNotFoundException when reading from FileInputStream

androidfilenotfoundexception

I am trying this code:

http://androidgenuine.com/?tag=export-database-android

By using this code in my example, I am always getting a FileNotFoundException, though the folder exists in external storage while reading FileInputStream.

Here is my code:

public void exportdata()
    {

        try 
        {

            myInput = new FileInputStream("/data/data/com.example.hello/databases/BikeMaintenance.db");
            File directory = new File("/sdcard/BikeMaintenance/Data/");
            // Create the folder if it doesn't exist:
            if (!directory.exists()) 
            {
                directory.mkdirs();
            } 

            OutputStream myOutput = new FileOutputStream(directory.getPath()+"/BikeMaintenance.backup");
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer))>0)
            {

                myOutput.write(buffer, 0, length);
                msg="Backup Succesfull!";
                Toast.makeText(MainPage.this,msg,Toast.LENGTH_SHORT).show();
            }
            // Close and clear the streams
            myOutput.flush();
            myOutput.close();        
            myInput.close();
        }
        catch (FileNotFoundException e) 
        {
            msg="FileNotFoundException";
            Toast.makeText(MainPage.this,msg,Toast.LENGTH_SHORT).show();

            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            msg="Backup Unsuccesfull!";
            Toast.makeText(MainPage.this,msg,Toast.LENGTH_SHORT).show();
        }

    }

Where am I going wrong? What may be the reason for this? I searched solution for this, but didn't find a solution.

Here is the logcat output:

java.io.FileNotFoundException:
/data/data/com.example.hello/databases/BikeMaintenance.db: open
failed: ENOENT (No such file or directory)
  at libcore.io.IoBridge.open(IoBridge.java:416)
  at java.io.FileInputStream.(FileInputStream.java:78)
  at java.io.FileInputStream.(FileInputStream.java:105)
  at com.example.hello.MainPage.exportdata(MainPage.java:625)
  at com.example.hello.MainPage.backup(MainPage.java:692)
  at com.example.hello.MainPage$1.onClick(MainPage.java:494)
  at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
  at android.os.Handler.dispatchMessage(Handler.java:99)
  at android.os.Looper.loop(Looper.java:137)
  at android.app.ActivityThread.main(ActivityThread.java:4745)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:511)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
  at dalvik.system.NativeStart.main(Native Method)
Caused by: libcore.io.ErrnoException: open failed:
ENOENT (No such file or directory)
  at libcore.io.Posix.open(Native Method)
  at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
  at libcore.io.IoBridge.open(IoBridge.java:400)
  ... 14 more

Best Answer

your code looks good to me but What i think is you dont have permission to access that .db file you can use DataBaseHelper class to access your .db file

    public class DataBaseHelper extends SQLiteOpenHelper {

     private static String DB_PATH = "/data/data/com.android.electricbillgenerator/databases/";

        private static String DB_NAME = "BikeMaintenance.db";

        private SQLiteDatabase myDataBase;

        private Context myContext;

        public static final String COLUMN_ID = "_id";
        public static final String COLUMN_USERNAME = "UserName";
        public static final String COLUMN_PASSWORD = "Password";
        public static final String TABLE_NAME = "Login";
        private static final String DATABASE_NAME = "BikeMaintenance.db";
        private static final int DATABASE_VERSION = 1;

     // Database creation sql statement
//      private static final String DATABASE_CREATE = "create table "
//          + TABLE_NAME + "(" + COLUMN_ID
//          + "," + COLUMN_USERNAME
//          + "," + COLUMN_PASSWORD+ ");";

//      private static final String DATABASE_CREATE = "create table "
//              + TABLE_NAME + "(" + COLUMN_ID
//              + " integer primary key autoincrement, " + COLUMN_USERNAME
//              + " text not null," + COLUMN_PASSWORD+ "text not null);";

    public DataBaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 8);
        this.myContext = context;

         boolean dbexist = checkDataBase();
            if (dbexist) {
                //System.out.println("Database exists");
                openDataBase(); 
            } else {
                System.out.println("Database doesn't exist");
                try {
                    createDataBase();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

    }


    @Override
    public void onCreate(SQLiteDatabase database) {



//      try {
//          database.execSQL(DATABASE_CREATE);
//      } catch (SQLException e) {
//          // TODO Auto-generated catch block
//          e.printStackTrace();
//      }

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//      Log.w(DataBaseHelper.class.getName(),
//              "Upgrading database from version " + oldVersion + " to "
//                  + newVersion + ", which will destroy all old data");
//          db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
//          onCreate(db);

    }




    /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public void createDataBase() throws IOException{

        boolean dbExist = checkDataBase();

        if(dbExist){
            //do nothing - database already exist
        }else{

            //By calling this method and empty database will be created into the default system path
               //of your application so we are gonna be able to overwrite that database with our database.
            this.getReadableDatabase();

            try {

                copyDataBase();

            } catch (IOException e) {

                throw new Error("Error copying database");

            }
        }

    }


    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(){

        SQLiteDatabase checkDB = null;

        try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

        }catch(SQLiteException e){

            //database does't exist yet.

        }

        if(checkDB != null){

            checkDB.close();

        }

        return checkDB != null ? true : false;
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException{

        //Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;

        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        //transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }
    public void openDataBase() throws SQLException{

        //Open the database
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }

    @Override
    public synchronized void close() {

            if(myDataBase != null)
                myDataBase.close();

            super.close();

    }



}
Related Topic