An output stream that writes bytes to a file. If the output file exists, it can be replaced or appended to. If it does not exist, a new file will be created.
1. Declare and Set an OutputStream named myOutputStream and set to null;
2. In the MainActivity.java file, add the following the to imports section.
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.IOException;
3. Add the code below to the onCreate method. It must be enclosed in a try/catch. Replace mypackagename with your package name. Replace mySQLiteDatabase.db with your file name.
try {
myOutputStream = new FileOutputStream("/data/data/mypackagename/mySQLiteDatabase.db");
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally { if (myOutputStream != null) { try { myOutputStream.close(); } catch (IOException e) {
e.printStackTrace(); } } }
myOutputStream = new FileOutputStream("/data/data/mypackagename/mySQLiteDatabase.db");
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally { if (myOutputStream != null) { try { myOutputStream.close(); } catch (IOException e) {
e.printStackTrace(); } } }
4. Compile and run!
* Note: myOutputStream.flush() is not needed before the close() because the myOutputStream.close() does a flush and a close.
Resources: