Work with IO Stream in Java

In java, one can divide streams into two main types:

  • Connection streams, which Java use to directly connect to the source data (File on external memory, Network stream…):
    – FileInputStream/ FileOutStream is used to read binary file
    – FileReader/FileWriter is used to work with text file
    ….
  • Filter streams, or chain streams, used to wrap these connection streams in order to give it more functionality.
    – BufferedInputStream /BufferedOutputStream used to chain binary file
    – BufferedReader/ BufferedWriter used to chain text file

And here are some examples describing the typical way to:

  • Read / Write to binary file
  • Read / Write to text file
  • Read / Write to object (when using serializable)

1. Read / Write to binary file

Read:

package com.nxhoaf.io.binary;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

public class MyBinaryFileReader {
    public static void main(String[] args) {
        try {
            // Create the source
            File file = new File("resources/input.bin");
            // Create a "connection" stream, which connect directly to source
            FileInputStream fis = new FileInputStream(file);
            // Create a "chain" (or "filter") stream
            BufferedInputStream bis = new BufferedInputStream(fis);

            // We temporally store the whole content here
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = bis.read(buffer)) > 0) {
                baos.write(buffer, 0, length);
            }

            // Ok, get the whole content
            byte[] content = baos.toByteArray();
            for (byte b : content) {
                // Convert to int to apply Integer method
                // here, we use byte to store bits, so, use bit mask to convert
                // unsigned byte to int
                int i = b & 0xFF;
                System.out.print(Integer.toHexString(i) + "");

                // For more info:
                // int i = 234;
                // byte b = (byte) i;
                // System.out.println(b); // -22
                // int i2 = b & 0xFF;
                // System.out.println(i2); // 234
            }

            baos.close();
            bis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Writer:

package com.nxhoaf.io.binary;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

public class MyBinaryFileWriter {
    public static void main(String[] args) {
        try {
            // Create the source
            File file = new File("resources/output.bin");
            // Create a "connection" stream, which connect directly to source
            FileOutputStream fos = new FileOutputStream(file);
            // Create a "chain" (or "filter") stream
            BufferedOutputStream bos = new BufferedOutputStream(fos);

            byte[] bytes = {
                    0x48,// H
                    0x65,// e
                    0x6C,// l
                    0x6C,// l
                    0x6F,// o
            };

            bos.write(bytes);
            bos.close();

            // As the content is in binary form (not human-readable), we cannot
            // read it, use this tool instead to check the file content
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2.Read / Write to text file
Read:

package com.nxhoaf.io.text;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

/**
 * TextFileReader demo
 * @author nxhoaf
 *
 */
public class MyTextFileReader {
    public static void main(String[] args) {
        try {
            // Create the source
            File file = new File("resources/input-text.txt");
            // Create a "connection" stream, which connect directly to source
            FileReader fileReader = new FileReader(file);
            // Create a "chain" (or "filter") stream
            BufferedReader reader = new BufferedReader(fileReader);

            String line = "";
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

And write:

package com.nxhoaf.io.text;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

/**
 * TextFileWriter demo
 * @author nxhoaf
 *
 */
public class MyTextFileWriter {
    public static void main(String[] args) {
        try {
            // Create the source
            File file = new File("resources/output-text.txt");
            // Create a "connection" stream, which connect directly to source
            FileWriter fileWriter = new FileWriter(file);
            // Create a "chain" (or "filter") stream
            BufferedWriter writer = new BufferedWriter(fileWriter);

            String[] lines = {"one", "two", "three"};

            for (String line : lines) {
                writer.write(line + "\n");
            }

            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3. Read / Write to object (when using serializable)
We’ll use Person.java class described below to test the read/write
Person class:

package com.nxhoaf.io.object;

import java.io.Serializable;

public class Person implements Serializable {
    private static final long serialVersionUID = 1091172054761152924L;
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String toString() {
        String result = "";
        result += Person.class.getName() + "\n";
        result += "name: " + name + " age: " + age;
        return result;
    }
}

Read:

package com.nxhoaf.io.object;

import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;

/**
 * ObjectReader demo
 * @author nxhoaf
 *
 */
public class MyObjectReader {
    public static void main(String[] args) {
        try {
            // Create the source
            File file = new File("resources/input.obj");
            // Create a "connection" stream, which connect directly to source
            FileInputStream fis = new FileInputStream(file);
            // Create a "chain" (or "filter") stream
            ObjectInputStream oos = new ObjectInputStream(fis);

            Person p1 = (Person) oos.readObject();
            Person p2 = (Person) oos.readObject();

            System.out.println(p1);
            System.out.println(p2);

            oos.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Write:

package com.nxhoaf.io.object;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

/**
 * ObjectWriter demo
 * @author nxhoaf
 *
 */
public class MyObjectWriter {
    public static void main(String[] args) {
        try {
            // Create the source
            File file = new File("resources/output.obj");
            // Create a "connection" stream, which connect directly to source
            FileOutputStream fos = new FileOutputStream(file);
            // Create a "chain" (or "filter") stream
            ObjectOutputStream oos = new ObjectOutputStream(fos);

            Person[] persons = {
                    new Person("Peter", 11),
                    new Person("Mary", 21)
            };

            for (Person p : persons) {
                oos.writeObject(p);
            }

            oos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Advertisements
This entry was posted in Java and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s