Skip to content

Instantly share code, notes, and snippets.

@Tanapruk
Last active November 25, 2020 11:09
Show Gist options
  • Select an option

  • Save Tanapruk/db3effe6f505b7ff2f63ca7674e02722 to your computer and use it in GitHub Desktop.

Select an option

Save Tanapruk/db3effe6f505b7ff2f63ca7674e02722 to your computer and use it in GitHub Desktop.
Input and Output Stream of Java

Page 1

I/O

When using Input or Output with java programming. We have serveral ways of implementing them. At the smallest and lowest level possible is FileInputStream and FileOutputStream. As the names describe one is for input the other is for output.

  • Input - read files/read log
  • Output - write files/print to log

FileInputStream and FileOutputStream.

  • Read byte-by-byte
public class CopyBytes {
    public static void main(String[] args) throws IOException {

        FileInputStream in = null;
        FileInputStream in2 = null;
        FileOutputStream out = null;

        try {
            in = new FileInputStream("xanadu.txt");
            out = new FileOutputStream("outagain.txt");
            int c;
            String as = "";

            while ((c = in.read()) != -1) {
                System.out.println("c is " + c + " & it is " + (char) c);
                as = as + (char) c;
                System.out.println("total\n'" + as + "'");
                out.write(c);
            }
        } finally {
            if (in != null) {
                in.close();
            }

            if (out != null) {
                out.close();
            }
        }
    }
}

In xanadu.txt we have hello. Running the above method would produce.

c is 104 & it is h
total
'h'
c is 101 & it is e
total
'he'
c is 108 & it is l
total
'hel'
c is 108 & it is l
total
'hell'
c is 111 & it is o
total
'hello'
c is 10 & it is 

total
'hello
'

c is 104 & it is h 104 is the ASCII code for character h.

source

Page 2

FileReader and FileWriter

Compare with FileInputStream/FileOutputStream the FileReader/FileWriter is more sophisicated. E.g., it can read/write Unicode instead of ASCII.

  • FileInputStream/FileOutputStream read and write in 8 bit.
  • FileReader/FileWriter read and write in 16 bit.

BufferedReader and PrintWriter

This one will wrap the FileReader and FileWriter and print them line-by-line. It will detect linebreak symbols of "\r\n", "\r", "\n"

  BufferedReader inputStream = null;
  PrintWriter outputStream = null;
  
  //wrap new FileReader(filename) and wrap new FileWriter(filename)
  inputStream = new BufferedReader(new FileReader("xanadu.txt"));
  outputStream = new PrintWriter(new FileWriter("characteroutput.txt"));

source

Page 3

FileInputStream/FileOutputStream/FileReader/FileWriter are unbuffered I/O

Unbuffered I/O - Expensive Operations. Frequent disk access or networks.

Buffered I/O - Stack I/O Operations before executing them all by once.

  • Output - write data to buffer and call the expensive when the buffer is full.
  • Input - buffer will read and keep data when it is empty.

Example,

    //the new FileReader() is wrapped inside BufferedReader
    //Also, the new FileWriter() is inside BufferedWriter
    inputStream = new BufferedReader(new FileReader("xanadu.txt"));
    outputStream = new BufferedWriter(new FileWriter("characteroutput.txt"));
Don't forget to flush

You shouldn't forget to clear the buffer with flush. Still, some Bufferred classes to the flush automatically after a method. E.g., println or format command.

source

Page 4

Scanner takes the Input Reading to the next level

  • Break down formatted input
  • can translate data

do it by wrapping the FileReader

  • Tripple wrapping!
new Scanner(new BufferedReader(new FileReader("xanadu.txt")));

Scanner in Action

 Scanner s = null;

        try {
            s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
            s.useDelimiter(",\\s*");

            while (s.hasNext()) {
                System.out.println(s.next());
            }
        } finally {
            if (s != null) {
                s.close();
            }
        }

With the above program, the result would be. It takes comma with a space as a token and reformat it.

  • Input - hello, sawasdee, nihao
  • Output
  hello
  sawasdee
  nihao

source

Page 5

print, println and format

The square root of 2 is 1.4142135623730951. To print log to the console with the above sentence, you can do as follows:

print - simply print

int i = 2;
double r = Math.sqrt(i);
System.out.print("The square root of ");
System.out.print(i);
System.out.print(" is ");
System.out.print(r);
System.out.println(".");

println - print and line break afterward

int i = 2;
double r = Math.sqrt(i);
System.out.println("The square root of " + i + " is " + r + ".");

format - print with a format with arguments that start with %

int i = 2;
double r = Math.sqrt(i); 
System.out.format("The square root of %d is %f.%n", i, r);

Page 6

DataInputStream and DataOutputStream automatically convert data types to/from I/O

E.g.,

  static final double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
  static final int[] units = { 12, 8, 13, 29, 50 };
  static final String[] descs = {
      "Java T-shirt",
      "Java Mug",
      "Duke Juggling Dolls",
      "Java Pin",
      "Java Key Chain"
  };

will be kept in txt file as:

  @3�p��
  =����Java T-shirt@#��G��{������Java Mug@/��G��{���
  ��Duke Juggling Dolls@����Q�������Java Pin@���\(����2��Java Key Chain

It looks gibberish! Because some symbols are encoded.

These unreadable texts can be converted back to their original form (the variable) without casting:

  double price;
  int unit;
  String desc;

The program of converting to .txt files is as follows:



    public static void main(String[] args) throws IOException {
      DataOutputStream out;
      //Wrap with DataOutputStream
      out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("invoicedata.txt")));
      try {
          for (int i = 0; i < prices.length; i++) {
              //each will have to specify type after the word write
              out.writeDouble(prices[i]);
              out.writeInt(units[i]);
              out.writeUTF(descs[i]);
          }
      } finally {
          if (out != null) {
              out.close();
          }

      }

  }

On the opposite end, when reading back we will use DataInputStream.

public static void main(String[] args) throws IOException {

        DataInputStream in;

        in = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile)));

        double price;
        int unit;
        String desc;
        double total = 0.0;

        try {
            while (true) {
                price = in.readDouble();
                unit = in.readInt();
                desc = in.readUTF();
                System.out.format("You ordered %d" + " units of %s at $%.2f%n",
                        unit, desc, price);
                total += unit * price;

            }
        } catch (EOFException e) {
            System.out.format("total %f", total);
        }
  }

source

# Page 7 ### `ObjectInputStream` and `ObjectOutputStream` convert object to/from I/O * This upgrades from `DataStream`. DataStream allows only primitive data type, while ObjectStream allows `Object` type. #### use `ObjectOutputStream` to serialize object into byte stream ```` public class WriteObjects { public static void main(String[] args) throws IOException { FileOutputStream fos = new FileOutputStream("t.tmp"); ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(fos)); oos.writeInt(12345); oos.writeObject("Today"); oos.writeObject(new Date()); oos.close(); } } ```` #### The byte stream in `t.tmp` file. ```` ���w�09t�Todaysr�java.util.Datehj��KYt��xpw��Y��G>x ```` #### To convert back to object from `t.tmp` file. ```` public class ReadObjects { public static void main(String[] args) throws IOException, ClassNotFoundException { FileInputStream fos = new FileInputStream("t.tmp"); ObjectInputStream oos = new ObjectInputStream(new BufferedInputStream(fos)); int aaa = oos.readInt(); String object = (String) oos.readObject(); Date dd = (Date) oos.readObject(); System.out.println(aaa); System.out.println(object); System.out.println(dd.toString()); oos.close(); } } ```` #### The result is ```` 12345 Today Fri Jan 27 11:08:32 ICT 2017 ```` [source1](http://docs.oracle.com/javase/tutorial/essential/io/objectstreams.html), [source2](https://docs.oracle.com/javase/8/docs/api/java/io/ObjectOutputStream.html)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment