Showing posts with label Files. Show all posts
Showing posts with label Files. Show all posts

How to Create a new FileOutputStream

FileOutputStream was added in API Level 1
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;

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(); } } }

4. Compile and run!

* Note: myOutputStream.flush() is not needed before the close() because the myOutputStream.close() does a flush and a close.

Resources:
Web hosting

How to Declare and Set an OutputStream

OutputStream was added in API Level 1
A writable sink for bytes. Most clients will use output streams that write data to the file system, the network, or to an in-memory byte array.

1. In the MainActivity.java file, add the line below to the imports section.

      import java.io.OutputStream;

2.Add the code below to the onCreate method. This will declare an OutputStream named myOutputStream and set it to null.

OutputStream myOutputStream = null;

3. Compile and run!

Next Recommended Article: How to Create a new FileOutputStream

Resources:

How to Declare and Set an InputStream

InputStream was added in API Level 1
A readable source of bytes.Most clients will use input streams that read data from the file system, the network, or from an in-memory byte array.

1. Create an Android project, if you don't already have one.

2. In the MainActivity.java file, add the line below to the imports section.

      import java.io.InputStream;

3.Add the code below to the onCreate method. This will declare the InputStream and set it to null.

InputStream myInputStream = null; 

4. Compile and run!

Next Recommended Article: How to Open an InputStream