Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I use this code in the <code>SQLiteOpenHelper</code> in one of my applications to import a database file.</p> <p>EDIT: I pasted my <code>FileUtils.copyFile()</code> method into the question.</p> <p><strong>SQLiteOpenHelper</strong></p> <pre><code>public static String DB_FILEPATH = "/data/data/{package_name}/databases/database.db"; /** * Copies the database file at the specified location over the current * internal application database. * */ public boolean importDatabase(String dbPath) throws IOException { // Close the SQLiteOpenHelper so it will commit the created empty // database to internal storage. close(); File newDb = new File(dbPath); File oldDb = new File(DB_FILEPATH); if (newDb.exists()) { FileUtils.copyFile(new FileInputStream(newDb), new FileOutputStream(oldDb)); // Access the copied database so SQLiteHelper will cache it and mark // it as created. getWritableDatabase().close(); return true; } return false; } </code></pre> <p><strong>FileUtils</strong></p> <pre><code>public class FileUtils { /** * Creates the specified &lt;code&gt;toFile&lt;/code&gt; as a byte for byte copy of the * &lt;code&gt;fromFile&lt;/code&gt;. If &lt;code&gt;toFile&lt;/code&gt; already exists, then it * will be replaced with a copy of &lt;code&gt;fromFile&lt;/code&gt;. The name and path * of &lt;code&gt;toFile&lt;/code&gt; will be that of &lt;code&gt;toFile&lt;/code&gt;.&lt;br/&gt; * &lt;br/&gt; * &lt;i&gt; Note: &lt;code&gt;fromFile&lt;/code&gt; and &lt;code&gt;toFile&lt;/code&gt; will be closed by * this function.&lt;/i&gt; * * @param fromFile * - FileInputStream for the file to copy from. * @param toFile * - FileInputStream for the file to copy to. */ public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException { FileChannel fromChannel = null; FileChannel toChannel = null; try { fromChannel = fromFile.getChannel(); toChannel = toFile.getChannel(); fromChannel.transferTo(0, fromChannel.size(), toChannel); } finally { try { if (fromChannel != null) { fromChannel.close(); } } finally { if (toChannel != null) { toChannel.close(); } } } } } </code></pre> <p>Don't forget to delete the old database file if necessary.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload