Over

120,000

Worldwide

Saturday - Sunday CLOSED

Mon - Fri 8.00 - 18.00

Call us

 

Java IO

Java IO

Input / Output Streams

Java I/O is for processing the input and producing the output. It is all contained in java.io package. But this package doesn’t actually cover all the ways of inputting and outputting, for example input and output to a GUI or web page isn’t contained here. They have other packages covering the ways for Swing projects, Servlets and others.

Java IO package is mainly for input and output of files, network streams, internal memory buffers etc. Java IO contains many subclasses of the InputStream, OutputStream, Reader and Writer classes. They all have their purposes, for example:

File Access

Network Access

Internal Memory Buffer Access

Inter-Thread Communication (Pipes)

Buffering

Filtering

Parsing

Reading and Writing Text (Readers / Writers)

Reading and Writing Primitive Data (long, int etc.)

Reading and Writing Objects

Java IO API contains classes which are intended for working with files:

File

RandomAccessFile

FileInputStream

FileReader

FileOutputStream

FileWriter

Here you can see a picture which shows more precisely the work of JavaInputStream and JavaOutputStream.

Input Streams

Input streams read the data from the input source. The input source can be a file, line or memory, so anything that can hold data in it. All the input streams inherit an abstract class InputStream. This class defines a programming interface for reading bytes or arrays of bytes, skipping bytes of input, finding out the number of bytes which are available for reading, resetting the current position within the stream.

The hierarchy of input stream is more understandable drawn below:

An input stream is automatically opened when you create it. You can either close the stream with the close() method, or just let it be called when the object is collected by garbage collector.

An example of Input streams you can see below. This is an example of FileInputStream:

public class FileInputStreamExample {

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

byte[] array = new byte[100];

try {

InputStream inputStream = new FileInputStream(“input.txt”);

System.out.println(“Available bytes in the file: ” + inputStream.available());

inputStream.read(array);

System.out.println(“Data read from the file: “);

String data = new String(array);

System.out.println(data);

inputStream.close();

}

catch (Exception e) {

e.getStackTrace();

}

}

}

The output for this program will be:

Available bytes in the file: 35

Data read from the file:

An example of text, is written in file

In the program above, with read() method the byte is being read from the input stream. Then the byte array it is converted into string, and closed the stream.

Another example can be from ByteArrayInputStream:

public class ByteArrayInputStreamExample {

public static void main(String[] args) {

byte[] bytesArray = {7, 9, 5, 6};

try {

ByteArrayInputStream input = new ByteArrayInputStream(bytesArray); System.out.print(“Bytes from the inputStream: “);

for (int i = 0; i < bytesArray.length; i++) {

int data = input.read();

System.out.print(data + “, “);

}

input.close();

} catch (Exception e) {

e.getStackTrace();

}

}

}

The output is:

Bytes from the inputStream: 7, 9, 5, 6,

Here are given the bytes in an array, and with the help of ByteArrayInputStream we read the bytes from the array and in the end close the inputStream.

Another example of input stream is PipedInputStream:

public class PipedInputStreamExample {

public static void main(String[] args) {

PipedInputStream inputStream = new PipedInputStream();

PipedOutputStream outputStream = new PipedOutputStream();

try {

inputStream.connect(outputStream);

outputStream.write(72);

System.out.println(“using read() method: ” + (char) inputStream.read()); outputStream.write(70);

System.out.println(“using read() method: ” + (char) inputStream.read()); outputStream.write(74);

System.out.println(“using read() method: ” + (char) inputStream.read()); } catch (IOException e) {

e.printStackTrace();

}

}

}

The output is:

using read() method: H

using read() method: F

using read() method: J

With the connect() method it connects inputStream with outputStream. And reads the data with the read() method inside the stream.

Output Streams

Output Streams are used for writing data to an output source. Similar to input sources, the output source can contain file, string or memory.

The output stream hierarchy is this:

An example of output streams you can see below. This is an example of FileOutputStream:

public class FileOutputStreamExample {

public static void main(String[] args) {

String data = “An example of text, is written in file.”;

try {

OutputStream out = new FileOutputStream(“output.txt”);

byte[] dataBytes = data.getBytes();

out.write(dataBytes);

System.out.println(“Already written in the file.”);

out.close();

}

catch (Exception e) {

e.getStackTrace();

}

}

}

The output is:

Already written in the file.

OutputStream also offers a flush() method. This forces any buffered output bytes to be written out to the target resource. In our case that resource is a file.

public class FileOutputStreamExample2 {

private static final String OUTPUT_FILE =

“C:\\Users\\Comp\\IdeaProjects\\JavaLessons\\testFile.txt”;

public static void main(String[] args) {

String content = “This is example for flush”;

byte[] bytes = content.getBytes();

try (OutputStream out = new BufferedOutputStream(new FileOutputStream(OUTPUT_FILE), 1024)) {

out.write(bytes);

out.write(bytes[0]);

out.write(bytes, 4, 10);

out.flush();

} catch (IOException e) {

e.printStackTrace();

}

}

}

After executing this code in the file testFile.txt there will be written:

This is example for flushT is exampl

At first with write() method it writes bytes sequence, then it adds a single byte in the file. In the third call of write() method we give to it 3 parameters, and it writes a sub sequence of the byte array, and with flush() method it flushes the outstream.

Another example of output streams is ObjectOutputStream:

public class ObjectOutputStreamExample {

public static void main(String[] args) {

int integerData = 5;

String stringData = “This is an example”;

try {

FileOutputStream file = new FileOutputStream(“newFile.txt”);

ObjectOutputStream output = new ObjectOutputStream(file);

output.writeInt(integerData);

output.writeObject(stringData);

FileInputStream fileStream = new FileInputStream(“newFile.txt”);

ObjectInputStream objStream = new ObjectInputStream(fileStream);

System.out.println(“Integer data: ” + objStream.readInt());

System.out.println(“String data: ” + objStream.readObject());

output.close();

objStream.close();

} catch (Exception e) {

e.getStackTrace();

}

}

}

It will create the newFile.txt and write the data in it. The output will be:

Integer data: 5

String data: This is an example

As another example for object serialization and deserialization can be this: import java.io.*;

class Demo implements java.io.Serializable {

public int number;

public String string;

public Demo(int number, String string) {

this.number = number;

this.string = string;

}

}

class Test {

public static void main(String[] args) {

Demo object = new Demo(1, “This is an example”); String filename = “ourFile.ser”;

try {

FileOutputStream file = new FileOutputStream(filename); ObjectOutputStream out = new ObjectOutputStream(file);

out.writeObject(object);

out.close();

file.close();

System.out.println(“Serialized!”);

} catch (IOException ex) {

System.out.println(“IOException found”);

}

Demo object1 = null;

try {

FileInputStream file = new FileInputStream(filename); ObjectInputStream in = new ObjectInputStream(file);

object1 = (Demo) in.readObject();

in.close();

file.close();

System.out.println(“Deserialized!”);

System.out.println(“number = ” + object1.number); System.out.println(“string = ” + object1.string);

} catch (IOException ex) {

System.out.println(“IOException found”);

} catch (ClassNotFoundException ex) {

System.out.println(“ClassNotFoundException found”);

}

}

}

Here we have the Demo object, which has just a number and a string in it. It is being serialized, meaning it is writing the object into a byte-stream. For that we use writeObject() method from ObjectOutputStream. For deserialization we use readObject() method of ObjectInputStream class.

The purpose for this process of converting a stream into a stream of bytes is to store the object or transmit it to memory, a database, or a file. It can be recreated when needed.

The output for this will be:

Serialized!

Deserialized!

number = 1

string = This is an example

Another example can be with the Inter Thread Communication. All the stacks of threads of a given process are still in the same address space. You can use IPC mechanism between threads, for example you can have an object and have on thread writing it and another reading it.

import java.util.Scanner;

public class IPCExample {

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

final PC pc = new PC();

Thread t1 = new Thread(() -> {

try {

pc.produce();

} catch (InterruptedException e) {

e.printStackTrace();

}

});

Thread t2 = new Thread(() -> {

try {

pc.consume();

} catch (InterruptedException e) {

e.printStackTrace();

}

});

t1.start();

t2.start();

t1.join();

t2.join();

}

public static class PC {

public void produce() throws InterruptedException {

synchronized (this) {

System.out.println(“producer thread running”);

wait();

System.out.println(“Resumed”);

}

}

public void consume() throws InterruptedException {

Thread.sleep(1000);

Scanner s = new Scanner(System.in);

synchronized (this) {

System.out.println(“Waiting for return key.”);

s.nextLine();

System.out.println(“Return key pressed”);

notify();

Thread.sleep(2000);

}

}

}

}

The output is:

producer thread running

Waiting for return key.

Return key pressed

Resumed

The code above we can explain like this. It created a thread object that calls pc.produce(), then another thread which calls pc.consume() and start both of the threads. The first one finishes before first.

For the Produce Consumer (PC), in the produce() method it prints a string and waits for consume(). The synchronized block inside it, ensures that only one thread is running at a time. With the wait() method it releases the lock on shared resource and then waits till some other method invokes notify().

In the consume() method, it sleeps for some time and waits for a key press. After key is pressed, it notifies produce(). With sleep() method it makes the produce thread to run first. And in the synchronized block ensures only one thread is running at a time. Then it notifies the produce thread that it can wake up and calls sleep().

Leave a Reply

Your email address will not be published. Required fields are marked *

Working Hours

  • Monday 9am - 6pm
  • Tuesday 9am - 6pm
  • Wednesday 9am - 6pm
  • Thursday 9am - 6pm
  • Friday 9am - 6pm
  • Saturday Closed
  • Sunday Closed