javaandroidandroid-sqlitefileoutputstreamandroid-assets

Creating database file in application data


I read similar questions and answers, but none working for me. I am trying copying sqlite database from assets folder to application data folder, but this always fail, because target database file is not created.

TRY 1:

databasePath = context.getApplicationInfo().dataDir + "/databases/test.db";

Path path = Paths.get(databasePath);

OutputStream applicationDatabaseStream = Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE);

Fails with exception:

W/System.err: java.nio.file.NoSuchFileException: /data/user/0/eu.example.test/databases/test.db

TRY 2:

databasePath = context.getApplicationInfo().dataDir + "/databases/test.db";

OutputStream applicationDatabaseStream = new FileOutputStream(databasePath);

Fails with exception:

W/System.err: java.io.FileNotFoundException: /data/user/0/eu.example.test/databases/test.db: open failed: ENOENT (No such file or directory)

Whats wrong with this code?

I expect that code create file in application data folder.


Solution

  • You can't create a path like that. context.getApplicationInfo().dataDir + "/databases/test.db"; The dataDir will exist, but nobody has yet created the databases subdirectory. So it won't exist, which means opening test.db will fail. You have to create the entire directory tree first.