Skip to main content

Java InputOutput Types

Java InputOutput :
Most of the application needs to process some input and then produce output to a network file or local file etc.
There is a java package java.io which provides input and output through data streams , serialization and the file system.

The package covers most of the input and output operations required but not the GUI I/O operations which are covered in Swing, JSP etc in Java enterprise.

this package is primarily focused on input and output to files, network streams, internal memory buffers etc. However, the Java IO package does not contain classes to open network sockets which are necessary for network communication.
For opening network sockets there is another networking package in java.

Typical Java IO sources : FILE, Network IO, Streams

Streams: Conceptually, a stream is a endless flow of data from where you can either read  or write .
Streams in Java IO can be either byte based (reading and writing bytes) or character based (reading and writing characters).
For reading data : InputStream or Reader is used
For writing data : OutputStream or Writer is used



Where Input and Output Stream classes are Byte based streams and other are character based.
It means the InputStream and the OutputStream reads/writes data byte by byte
and the other one character by character.

Example classes of InputStream, and OutputStream : ByteArrayInputStream, ByteArrayOutputStream, FileInputStream,FileOutputStream,
PipedInputStream, PipedOutputStream , BufferedInputStream, BufferedOutputStream, FilterInputStream, FilterOutputStream, ObjectInputStream, ObjectOutputStream

 

Examples of Reader and writer Input/Output Stream : InputStreamReader, OutputStreamWriter,
CharArrayReader, CharArrayWriter, FileReader, FileWriter, PipedReader, PipedWriter, BufferedReader, BufferedWriter, FilterReader, FilterWriter, StringReader, StringWriter


and there is one utility input stream where you can give multiple Streams input : SequenceInputStream
 



FileReader is for character oriented operation.

FileInputStream and FileReader extends InputStream and InputStreamReader classes respectively.

Both InputStream and Reader are abstractions to read data from source, which can be either file or socket, but main difference between them is, InputStream is used to read binary data, while Reader is used to read text data, precisely Unicode characters.
So what is difference between binary and text data? well everything you read is essentially bytes, but to convert a byte to text, you need a character encoding scheme. Reader classes uses character encoding to decode bytes and return characters to caller. Reader can either use default character encoding of platform on which your Java program is running or accept a Charset object or name of character encoding in String format e.g. "UTF-8".

Abstract class input stream is extended by 5 classes : PipedInputStream, FileInputStream, ByteArrayInputStream, ObjectInputStream, FilterInputStream.


To randomly access the file you can use RandomAccessFile.



File: Files are very common source and destination for IO.


Here is an example of creating a file and writing using byte stream writ
er :


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class CreateAndWriteFile {
    public static void main(String[] args) {

        FileOutputStream fop = null;
        File file;
        String content = "Create And Write File Example";

        try {

            file = new File(System.getProperty("user.home"), "/abc.txt");
            // if file doesnt exists, then create it
                        if (!file.exists()) {
                            file.createNewFile();
                        }
            fop = new FileOutputStream(file);

          

            // get the content in bytes
            byte[] contentInBytes = content.getBytes();

            fop.write(contentInBytes);
            fop.flush();
            fop.close();

            System.out.println("Done");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fop != null) {
                    fop.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


You can get and set the file permissions using below methods:

setExecutable(boolean); setReadable(boolean); setWritable(boolean);
canExecute(); canWrite(); canRead();


to set absolute permission you can use the below:

Runtime.getRuntime().exec("chmod 777 file");
  

Buffered Reader/ Writer:  The BufferedReader and BufferedWriter class can wrap around Readers/Writers like FileReader, to buffer the input and improve efficiency.

These class helps to improve the efficiency because they read and write multiple characters at a time however file reader /writer class reads only one or two bytes at a time.

To use BufferedReader object you need to specify which stream you want to buffer.
For example:

BufferedReader br = new BufferedReader( new FileReader("Sample.txt") ); //Reads one line from the file at a time

The buffer size may be specified, or the default size may be used.
The default is large enough for most purposes.

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream.
BufferedReader(Reader in) : Creates a buffering character-input stream that uses a default-sized input buffer.
BufferedReader(Reader in, int size): Creates a buffering character-input stream that uses an input buffer of the specified size.

Buffered Writer is also similar to BufferedReader , except that is it is used for output.

You can wrap the BufferedWriter around any output stream to buffer the output.

BufferedWriter bw = new BufferedWriter(new FileWriter("fileName.txt"));
   bw.write("hello");

 


Pipes: It is used to communicate between threads. The piped input stream is connected to piped output stream. Data is read from PipedInputStream and written to PipedOutputStream.
The reading and writing threads should be different. Using the same thread may leads to deadlock as the read() and write() calls are blocking.

The pipe concept in Java is different from that in Linux/Unix as in java piped communication is done between two threads of the same object, however in other that is done between two different process.
The piped Input stream contains a buffer which decouples read operation from write operation within limits.








Comments

Popular posts from this blog

OBJECT class in Java

OBJECT class in Java : Object is at the top of class hierarchy in java. Every class in the Java system is a descendent (direct or indirect) of the Object class. The Object class defines the basic state and behavior that all objects must have, such as the ability to compare oneself to another object, to convert to a string, to wait on a condition variable, to notify other objects that a condition variable has changed, and to return the object's class. Mainly below methods are provided by Object class : public String toString() returns the string representation of this object. protected Object clone() throws CloneNotSupportedException creates and returns the exact copy (clone) of this object. public boolean equals(Object obj) compares the given object to this object. public int hashCode() returns the hashcode number for this object. public final Class getClass() returns the Class class object of this object. The Class class can further be used to get the metadata of ...

Java Priority Queue sort using lambda expression

Priority Queue :     In Java  Priority Queue  is a  queue  which keeps its elements sorted as per their natural order( example in ascending orders for Integer, alphabetical a-z for alphabets) or using a custom Comparator at the time of creation you can custom sort it. It has most method  similar to a queue  add, clear, poll, peek As priority queue have to compare elements to keep in order so elements must be comparable otherwise, it will throw ClassCastException .  As null can not be compared so you are not allowed to insert null too A program to sort priority queue using Lambda function in Java           c lass   PriorityQueueLambdaJava { public List<Integer> KFrequent( int [] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); for ( int j: nums) { map .put(j, map .getOrDefault(j, 0 ) + 1 ); } PriorityQueue<Map.Entry<Integ...

Important Keywords: Static, Continue,Break:

Important Keywords: Static, Continue,Break:  Static: The static keyword in java is used for memory management mainly.  The static keyword members belongs to the class rather than instance of the class. Following members can be declared as static: variable (also known as class variable) method (also known as class method) block nested class  static variables : We can use static keyword with a class level variable. A static variable is a class variable and doesn’t belong to Object/instance of the class. Since static variables are shared across all the instances of Object, they are not thread safe . Usually static variables are used with final keyword for common resources or constants that can be used by all the objects. If the static variable is not private, we can access it as: ClassName.variableName //static variable example private static int a ge; public static String name; static methods: A static method belongs t...