CORE JAVA: I/O Streams

Introduction

  • Java I/O (Input and Output) is used to process the input and produce the output.
  • Java uses the concept of the stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations.
  • We can perform file handling in Java by Java I/O API.

Stream: A sequence of data.

Input Stream: reads data from a source.

Output Stream: writes data to a destination.

Stream:

A stream is a sequence of data.In Java, a stream is composed of bytes. It’s called a stream because it is like a stream of water that continues to flow.

In java, 3 streams are created for us automatically. All these streams are attached to console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Let's see the code to print output and error message to the console.
System.out.println("simple message");  
System.err.println("error message");  

Let's see the code to get input from console.
int i=System.in.read();//returns ASCII code of 1st character  
System.out.println((char)i);//will print the character 

 Byte-oriented streams

It provides a convenient means for handling input & output of bytes.

InputStream:

Java application uses an input stream to read data from a source, it may be a file, an array, peripheral device or socket.

InputStream class

InputStream class is an abstract class. It is the super class of all classes representing an input stream of bytes.

Useful methods of InputStream

io1.png

 

 

io11.png

OutputStream:

Java application uses an output stream to write data to a destination, it may be a file, an array, peripheral device or socket.

OutputStream class

OutputStream class is an abstract class. It is the super class of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink.

Useful methods of OutputStream

io2.png

io22.png

Some important Byte Stream Classes:

  1. BufferedInputStream- used for I/S
  2. BufferedOutputStream- used for O/S
  3. DataInputStream- contains for reading Java Standard datatype
  4. DataOutputStream- An O/S that contains for writing Java Standard datatype
  5. FileInputStream- Input string that reads from a file
  6. FileOutputStream- Output string that writes to a file
  7. PrintStream- An Output string that contain print() & println()

Character- oriented streams

It provides a convenient means for handling input & output of Characters.Character Stream uses Unicode & therefore can be internationalized.

Reader:

  • Java Reader is an abstract class for reading character streams. The only methods that a subclass must implement are read(char[], int, int) and close(). Most subclasses, however, will override some of the methods to provide higher efficiency, additional functionality, or both.
  • Some of the implementation class are BufferedReader, CharArrayReader, FilterReader, InputStreamReader, PipedReader, StringReader
  • Example

    import java.io.*;  
public class ReaderExample {  

    public static void main(String[] args) {  

        try {  

            Reader reader = new FileReader("file.txt");  

            int data = reader.read();  

            while (data != -1) {  

                System.out.print((char) data);  

                data = reader.read();  

            }  

            reader.close();  

        } catch (Exception ex) {  

            System.out.println(ex.getMessage());  

        }  

    }  

}  
  • file.txt:  I love my country
  • Output: I love my country

Writer:

  • Java Writer is an abstract class for writing to character streams. The methods that a subclass must implement are write(char[], int, int), flush(), and close(). Most subclasses will override some of the methods defined here to provide higher efficiency, functionality or both.
  • Example

import java.io.*;

public class WriterExample {

public static void main(String[] args) {

try {

Writer w = new FileWriter(“output.txt”);

String content = “I love my country”;

w.write(content);

w.close();

System.out.println(“Done”);

catch (IOException e) {

e.printStackTrace();

}

}

}

  • Output: Done 
  • output.txt: I love my country

Some important Byte Stream Classes:

  1. BufferedReader- Handles buffered input stream
  2. BufferedWriter- Handles buffered output stream
  3. FileReader- Input stream that reads from file
  4. FileWriter- Output stream that writes to file
  5. InputStreamReader- Input stream that translates byte to character
  6. OutputStreamReader- Output stream that translates character to byte
  7. PrintWriter- Output stream that contain print() & println() method

Java.io.File Class in Java

The File class is Java’s representation of a file or directory path name. Because file and directory names have different formats on different platforms, a simple string is not adequate to name them. The File class contains several methods for working with the path name, deleting and renaming files, creating new directories, listing the contents of a directory, and determining several common attributes of files and directories.

  • It is an abstract representation of file and directory pathnames.
  • A pathname, whether abstract or in string form can be either absolute or relative. The parent of an abstract pathname may be obtained by invoking the getParent() method of this class.
  • First of all, we should create the File class object by passing the filename or directory name to it. A file system may implement restrictions to certain operations on the actual file-system object, such as reading, writing, and be executing. These restrictions are collectively known as access permissions.
  • Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.

How to create a File Object?

A File object is created by passing in a String that represents the name of a file, or a String or another File object. For example,

 File a = new File("/usr/local/bin/geeks");

defines an abstract file name for the geek’s file in directory /usr/local/bin. This is an absolute abstract file name.

Constructors 

  • File(File parent, String child): Creates a new File instance from a parent abstract pathname and a child pathname string.
  • File(String pathname): Creates a new File instance by converting the given pathname string into an abstract pathname.
  • File(String parent, String child): Creates a new File instance from a parent pathname string and a child pathname string.
  • File(URI uri) : Creates a new File instance by converting the given file: URI into an abstract pathname.

Methods

  1. boolean canExecute(): Tests whether the application can execute the file denoted by this abstract pathname.
  2. boolean canRead(): Tests whether the application can read the file denoted by this abstract pathname.
  3. boolean canWrite(): Tests whether the application can modify the file denoted by this abstract pathname.
  4. int compareTo(File pathname): Compares two abstract pathnames lexicographically.
  5. boolean createNewFile(): Atomically creates a new, empty file named by this abstract pathname .
  6. static File createTempFile(String prefix, String suffix): Creates an empty file in the default temporary-file directory.
  7. boolean delete(): Deletes the file or directory denoted by this abstract pathname.
  8. boolean equals(Object obj): Tests this abstract pathname for equality with the given object.
  9. boolean exists(): Tests whether the file or directory denoted by this abstract pathname exists.
  10. String getAbsolutePath() : Returns the absolute pathname string of this abstract pathname.
  11. long getFreeSpace() : Returns the number of unallocated bytes in the partition .
  12. String getName(): Returns the name of the file or directory denoted by this abstract pathname.
  13. String getParent(): Returns the pathname string of this abstract pathname’s parent.
  14. File getParentFile() : Returns the abstract pathname of this abstract pathname’s parent.
  15. String getPath(): Converts this abstract pathname into a pathname string.
  16. boolean isDirectory(): Tests whether the file denoted by this pathname is a directory.
  17. boolean isFile(): Tests whether the file denoted by this abstract pathname is a normal file.
  18. boolean isHidden(): Tests whether the file named by this abstract pathname is a hidden file.
  19. long length(): Returns the length of the file denoted by this abstract pathname.
  20. String[] list(): Returns an array of strings naming the files and directories in the directory .
  21. File[] listFiles() : Returns an array of abstract pathnames denoting the files in the directory.
  22. boolean mkdir(): Creates the directory named by this abstract pathname.
  23. boolean renameTo(File dest): Renames the file denoted by this abstract pathname.
  24. boolean setExecutable(boolean executable): A convenience method to set the owner’s execute permission.
  25. boolean setReadable(boolean readable): A convenience method to set the owner’s read permission.
  26. boolean setReadable(boolean readable, boolean ownerOnly): Sets the owner’s or everybody’s read permission.
  27. boolean setReadOnly(): Marks the file or directory named so that only read operations are allowed.
  28. boolean setWritable(boolean writable): A convenience method to set the owner’s write permission.
  29. String toString(): Returns the pathname string of this abstract pathname.
  30. URI toURI(): Constructs a file URI that represents this abstract pathname.

 Program to check if a file or directory physically exist or not.

// In this program, we accepts a file or directory name from

// command line arguments. Then the program will check if

// that file or directory physically exist or not and

// it displays the property of that file or directory.

*import java.io.File;

 

// Displaying file property

class fileProperty

{

    public static void main(String[] args) {

        //accept file name or directory name through command line args

        String fname =args[0];

 

        //pass the filename or directory name to File object

        File f = new File(fname);

 

        //apply File class methods on File object

        System.out.println("File name :"+f.getName());

        System.out.println("Path: "+f.getPath());

        System.out.println("Absolute path:" +f.getAbsolutePath());

        System.out.println("Parent:"+f.getParent());

        System.out.println("Exists :"+f.exists());

        if(f.exists())

        {

            System.out.println("Is writeable:"+f.canWrite());

            System.out.println("Is readable"+f.canRead());

            System.out.println("Is a directory:"+f.isDirectory());

            System.out.println("File Size in bytes "+f.length());

        }

    }

}

Output:

File name :file.txt
Path: file.txt
Absolute path:C:\Users\IdeaProjects\codewriting\src\file.txt
Parent:null
Exists :true
Is writeable:true
Is readabletrue
Is a directory:false
File Size in bytes 20

Java Random Access Files

  • Using a random access file, we can read from a file as well as write to the file.
  • Reading and writing using the file input and output streams are a sequential process.
  • Using a random access file, we can read or write at any position within the file.
  • An object of the RandomAccessFile class can do the random file access. We can read/write bytes and all primitive types values to a file.
  • RandomAccessFile can work with strings using its readUTF() and writeUTF() methods.
  • The RandomAccessFile class is not in the class hierarchy of the InputStream and OutputStream classes.

Mode

A random access file can be created in four different access modes. The access mode value is a string. They are listed as follows:

io22.png

Read and Write

  • We create an instance of the RandomAccessFile class by specifying the file name and the access mode
  • RandomAccessFile  raf = new RandomAccessFile("randomtest.txt", "rw");
  • A random access file has a file pointer that moves forward when we read data from it or write data to it.
  • The file pointer is a cursor where our next read or write will start.
  • Its value indicates the distance of the cursor from the beginning of the file in bytes.
  • We can get the value of file pointer by using its getFilePointer() method.
  • When we create an object of the RandomAccessFile class, the file pointer is set to zero.
  • We can set the file pointer at a specific location in the file using the seek() method.
  • The length() method of a RandomAccessFile returns the current length of the file. We can extend or truncate a file by using its setLength() method.

Example

The following code shows how to read and write Files Using a RandomAccessFile Object.

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
// w ww  .j av a  2s.  c  om
public class Main {
  public static void main(String[] args) throws IOException {
    String fileName = "randomaccessfile.txt";
    File fileObject = new File(fileName);

    if (!fileObject.exists()) {
      initialWrite(fileName);
    }
    readFile(fileName);
    readFile(fileName);
  }

  public static void readFile(String fileName) throws IOException {
    RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
    int counter = raf.readInt();
    String msg = raf.readUTF();

    System.out.println(counter);
    System.out.println(msg);
    incrementReadCounter(raf);
    raf.close();
  }

  public static void incrementReadCounter(RandomAccessFile raf)
      throws IOException {
    long currentPosition = raf.getFilePointer();
    raf.seek(0);
    int counter = raf.readInt();
    counter++;
    raf.seek(0);
    raf.writeInt(counter);
    raf.seek(currentPosition);
  }

  public static void initialWrite(String fileName) throws IOException {
    RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
    raf.writeInt(0);
    raf.writeUTF("Hello world!");
    raf.close();
  }
}

The code above generates the following result.

io22.png


Serialization

  • Serialization in java is a mechanism of writing the state of an object into a byte stream.
  • It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.
  • The reverse operation of serialization is called deserialization.

An advantage of Java Serialization:

It is mainly used to travel object’s state on the network (known as marshaling)java-serialization

ObjectOutputStream class:

The ObjectOutputStream class is used to write primitive data types and Java objects to an OutputStream. Only objects that support the java.io.Serializable interface can be written to streams.

Constructor:

1) public ObjectOutputStream(OutputStream out) throws IOException {} :creates an ObjectOutputStream that writes to the specified OutputStream.

Important Methods

Method Description
1) public final void writeObject(Object obj) throws IOException {} writes the specified object to the ObjectOutputStream.
2) public void flush() throws IOException {} flushes the current output stream.
3) public void close() throws IOException {} closes the current output stream.

An example of Java Serialization:

In this example, we are going to serialize the object of Student class. The writeObject() method of ObjectOutputStream class provides the functionality to serialize the object. We are saving the state of the object in the file named f.txt.

 

import java.io.*;  

class Persist{  

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

  Student s1 =new Student(211,“ravi”);  

  

  FileOutputStream fout=new FileOutputStream(“f.txt”);  

  ObjectOutputStream out=new ObjectOutputStream(fout);  

  

  out.writeObject(s1);  

  out.flush();  

  System.out.println(“success”);  

 }  

}  

Output: success

Deserialization in java

Deserialization is the process of reconstructing the object from the serialized state.It is the reverse operation of serialization.ObjectInputStream class.An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.

Constructor

1) public ObjectInputStream(InputStream in) throws IOException {} creates an ObjectInputStream that reads from the specified InputStream.

Important Methods

Method Description
1) public final Object readObject() throws IOException, ClassNotFoundException{} reads an object from the input stream.
2) public void close() throws IOException {} closes ObjectInputStream.

Example of Java Deserialization

 

import java.io.*;  

class Depersiste{  

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

    

  ObjectInputStream in=new ObjectInputStream(new FileInputStream(“f.txt”));  

  Student s=(Student)in.readObject();  

  System.out.println(s.id+” “+s.name);  

  

  in.close();  

 }  

}  

Output:

211 ravi

 

 

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s