top
Easter Sale

Search

Java Tutorial

To process the input and generate an output, Java I/O (Input and Output) is used. Java utilizes the stream idea to speed up the I/O operation. The java.io package includes all the classes which are necessary for input and output operations. We can use Java I/O API to handle files. The java.io package contains almost every class in Java that you may ever need to perform input and output (I / O). All these streams are a source of input and a destination of output. The stream in the java.io package supports a lot of information like primitives, object, localized characters, etc. Stream A stream can be described as a data sequence. There are two types of streams available: InPutStream: The InputStream is used from a source to read data. OutPutStream: To write data to a destination, the OutputStream is used in Java. Java offers powerful but flexible file and network I/O support, but this tutorial includes very fundamental stream and I/O functionality. We'll see one by one the most frequently used instances. Byte Streams Java byte streams are used to execute 8-bit bytes input and output. Although there are many classes linked to byte streams, FileInputStream and FileOutputStream are the most commonly used classes. Following is an instance to copy an input file into an output file using these two classes. Example: import java.io.*;  public class FileCopyExample {     public static void main(String args[]) throws IOException {          FileInputStream in = null;        FileOutputStream out = null;        try {           in = new FileInputStream("inputFile.txt");           out = new FileOutputStream("outputFile.txt");           int c;           while ((c = in.read()) != -1) {              out.write(c);           }        }finally {           if (in != null) {              in.close();           }           if (out != null) {              out.close();           }        }     }  } Let's have a document with the following content inputFile.txt: My first java stream program for file. Compile and execute the above-mentioned program as a next step, resulting in the creation of an outputFile.txt file with the same content as inputFile.txt. Character Streams Java Byte streams are used to execute 8-bit bytes input and output while Java Character streams are used to execute 16-bit Unicode input and output. Although there are many classes associated with character streams, FileReader and FileWriter are the most commonly used classes. While FileReader utilizes FileInputStream internally and FileWriter uses FileOutputStream, the main distinction here is that FileReader reads two bytes at one moment and FileWriter writes two bytes at one moment. The above instance can be re-written, which makes use of these two classes to copy an input file (with Unicode characters) into an output file. import java.io.*;  public class FileCopyExample {     public static void main(String args[]) throws IOException {        FileReader in = null;        FileWriter out = null;        try {           in = new FileReader("inputFile.txt");           out = new FileWriter("outputFile.txt");           int c;           while ((c = in.read()) != -1) {              out.write(c);           }        }finally {           if (in != null) {              in.close();           }           if (out != null) {              out.close();           }        }     }  } Let's have a document with the following content inputFile.txt: My first java stream program for file. Compile and execute the above-mentioned program as a next step, resulting in the creation of an outputFile.txt file with the same content as inputFile.txt. Standard Streams All programming languages support standard I/O, where the program of the user can take input from a keyboard and then generate an output on the screen of the computer. If you are aware of C or C++ programming languages, you must be aware of three standard devices STDIN, STDOUT and STDERR. Similarly, the following three normal streams are provided by Java. Standard Input: This is used to feed information into the program of the user and a keyboard is generally used as the standard input stream and displayed as System.in. Standard Output: This is used to output the user's program produced data and usually, a computer screen is used for the standard output stream and is represented as System.out. Standard Error: This is used to display the user program's error information and generally a computer screen is used and displayed as System.err for the standard error stream. Below is a basics program, which creates InputStreamReader to read standard input stream until the user types a "p". Example: import java.io.*;  public class MyFirstReadExample {     public static void main(String args[]) throws IOException {        InputStreamReader cin = null;        try {           cin = new InputStreamReader(System.in);           System.out.println("Enter characters, 'p' to quit.");           char c;           do {              c = (char) cin.read();              System.out.print(c);           } while(c != 'p');        }finally {           if (cin != null) {              cin.close();           }        }     } } Let's maintain the above code in MyFirstReadExample.java file and attempt compiling and executing it. This program keeps reading and displaying the same character until we press 'p’. Reading and Writing Files A stream can be defined as a series of information as outlined above. To read data from a source, the InputStream is used, while OutputStream is used to write data to a destination. Below is a class hierarchy to handle input and output streams in Java. FileInputStream and FileOutputStream are two significant streams in java. FileInputStream This stream is used to read file information. The new keyword can be used to create objects and several kinds of constructors are accessible. A file name is used as a string to produce an input stream object to read the file after the constructor. InputStream inputStream = new FileInputStream("C:/java/test"); It requires a file object to generate an input stream object after the constructor to read the file. First, we use the File () method to generate a file object as follows: File file = new File("C:/java/test");  InputStream inputStream = new FileInputStream(f); Once you have an InputStream object in hand, a list of helpful methods can be used to read to stream or perform other activities on the stream. Method & Descriptionpublic int read(int r)throws IOException{}This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned if it's the end of the file. It throws an IOException.protected void finalize()throws IOException {}This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. It throws an IOException.public void close() throws IOException{}The file output stream is closed by this method. Releases any file-related system resources. Throws an exception related to the IOE.public int available() throws IOException{}Gives the number of bytes that can be read from this file input stream. Returns an int. It throws an IOException.public int read(byte[] r) throws IOException{}This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read. If it is the end of the file, -1 will be returned. It throws an IOException.FileOutputStream To generate a file and enter information into it, FileOutputStream is used. If it does not already exist, the flow would generate a file before opening it for output. Here are two constructors that can be used to generate an object from FileOutputStream. To generate an input flow object to write the file, the following constructor requires a file name as a string: OutputStream outputStream = new FileOutputStream("C:/java/test")  A file object is used to generate an output stream object to write the file after the constructor. First, we use the File() method to generate a file object as follows: File file = new File("C:/java/test");  OutputStream outputStream = new FileOutputStream(f); Once you've got OutputStream object in hand, there's a list of helpful methods that can be used to write to stream or do other stream activities. Method & Descriptionprotected void finalize()throws IOException {}This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. It throws an IOException.public void close() throws IOException{}This method closes the file output stream. Releases any system resources associated with the file. It throws an IOException.public void write(byte[] w)Writes w.length bytes from the mentioned byte array to the OutputStream.public void write(int w)throws IOException{}This method writes the specified byte to the output stream. It throws an IOException.Example Below is the program to demonstrate InputStream and OutputStream in java: import java.io.*;  public class MyFileStreamProgram {     public static void main(String args[]) {        try {           byte bWrite [] = {121,201,31,140,25};           OutputStream os = new FileOutputStream("mytest.txt");           for(int x = 0; x < bWrite.length ; x++) {              os.write( bWrite[x] );            }           os.close();           InputStream is = new FileInputStream("mytest.txt");           int size = is.available();           for(int i = 0; i < size; i++) {              System.out.print((char)is.read() + "  ");           }           is.close();        } catch (IOException e) {           System.out.print("Exception");        }     } } The code above would generate the mytest.txt file and write the numbers provided in binary format. The same would be the stdout display output. 
logo

Java Tutorial

Files and I/O

To process the input and generate an output, Java I/O (Input and Output) is used. 

Java utilizes the stream idea to speed up the I/O operation. The java.io package includes all the classes which are necessary for input and output operations. 

We can use Java I/O API to handle files. 

The java.io package contains almost every class in Java that you may ever need to perform input and output (I / O). All these streams are a source of input and a destination of output. The stream in the java.io package supports a lot of information like primitives, object, localized characters, etc. 

Stream 

A stream can be described as a data sequence. There are two types of streams available: 

  • InPutStream: The InputStream is used from a source to read data. 
  • OutPutStream: To write data to a destination, the OutputStream is used in Java. 

Java offers powerful but flexible file and network I/O support, but this tutorial includes very fundamental stream and I/O functionality. We'll see one by one the most frequently used instances. 

Byte Streams 

Java byte streams are used to execute 8-bit bytes input and output. Although there are many classes linked to byte streams, FileInputStream and FileOutputStream are the most commonly used classes. Following is an instance to copy an input file into an output file using these two classes. 

Example: 

import java.io.*; 
public class FileCopyExample { 
   public static void main(String args[]) throws IOException {   
      FileInputStream in = null; 
      FileOutputStream out = null; 
      try { 
         in = new FileInputStream("inputFile.txt"); 
         out = new FileOutputStream("outputFile.txt"); 
         int c; 
         while ((c = in.read()) != -1) { 
            out.write(c); 
         } 
      }finally { 
         if (in != null) { 
            in.close(); 
         } 
         if (out != null) { 
            out.close(); 
         } 
      } 
   } 
} 

Let's have a document with the following content inputFile.txt: My first java stream program for file. 

Compile and execute the above-mentioned program as a next step, resulting in the creation of an outputFile.txt file with the same content as inputFile.txt. 

Character Streams 

Java Byte streams are used to execute 8-bit bytes input and output while Java Character streams are used to execute 16-bit Unicode input and output. Although there are many classes associated with character streams, FileReader and FileWriter are the most commonly used classes. While FileReader utilizes FileInputStream internally and FileWriter uses FileOutputStream, the main distinction here is that FileReader reads two bytes at one moment and FileWriter writes two bytes at one moment. 

The above instance can be re-written, which makes use of these two classes to copy an input file (with Unicode characters) into an output file. 

import java.io.*; 
public class FileCopyExample { 
   public static void main(String args[]) throws IOException { 
      FileReader in = null; 
      FileWriter out = null; 
      try { 
         in = new FileReader("inputFile.txt"); 
         out = new FileWriter("outputFile.txt"); 
         int c; 
         while ((c = in.read()) != -1) { 
            out.write(c); 
         } 
      }finally { 
         if (in != null) { 
            in.close(); 
         } 
         if (out != null) { 
            out.close(); 
         } 
      } 
   } 
} 

Let's have a document with the following content inputFile.txt: My first java stream program for file. 

Compile and execute the above-mentioned program as a next step, resulting in the creation of an outputFile.txt file with the same content as inputFile.txt. 

Standard Streams 

All programming languages support standard I/O, where the program of the user can take input from a keyboard and then generate an output on the screen of the computer. If you are aware of C or C++ programming languages, you must be aware of three standard devices STDIN, STDOUT and STDERR. Similarly, the following three normal streams are provided by Java. 

  • Standard Input: This is used to feed information into the program of the user and a keyboard is generally used as the standard input stream and displayed as System.in. 
  • Standard Output: This is used to output the user's program produced data and usually, a computer screen is used for the standard output stream and is represented as System.out. 
  • Standard Error: This is used to display the user program's error information and generally a computer screen is used and displayed as System.err for the standard error stream. 

Below is a basics program, which creates InputStreamReader to read standard input stream until the user types a "p". 

Example

import java.io.*; 
public class MyFirstReadExample { 
   public static void main(String args[]) throws IOException { 
      InputStreamReader cin = null; 
      try { 
         cin = new InputStreamReader(System.in); 
         System.out.println("Enter characters, 'p' to quit."); 
         char c; 
         do { 
            c = (char) cin.read(); 
            System.out.print(c); 
         } while(c != 'p'); 
      }finally { 
         if (cin != null) { 
            cin.close(); 
         } 
      } 
   } 
} 

Let's maintain the above code in MyFirstReadExample.java file and attempt compiling and executing it. This program keeps reading and displaying the same character until we press 'p’. 

Reading and Writing Files 

A stream can be defined as a series of information as outlined above. To read data from a source, the InputStream is used, while OutputStream is used to write data to a destination. 

Below is a class hierarchy to handle input and output streams in Java. 

Reading and Writing Files

FileInputStream and FileOutputStream are two significant streams in java. 

FileInputStream 

This stream is used to read file information. The new keyword can be used to create objects and several kinds of constructors are accessible. A file name is used as a string to produce an input stream object to read the file after the constructor. 

InputStream inputStream = new FileInputStream("C:/java/test"); 

It requires a file object to generate an input stream object after the constructor to read the file. First, we use the File () method to generate a file object as follows: 

File file = new File("C:/java/test"); 
InputStream inputStream = new FileInputStream(f); 

Once you have an InputStream object in hand, a list of helpful methods can be used to read to stream or perform other activities on the stream. 

Method & Description
public int read(int r)throws IOException{}

This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned if it's the end of the file. It throws an IOException.
protected void finalize()throws IOException {}

This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. It throws an IOException.
public void close() throws IOException{}

The file output stream is closed by this method. Releases any file-related system resources. Throws an exception related to the IOE.
public int available() throws IOException{}

Gives the number of bytes that can be read from this file input stream. Returns an int. It throws an IOException.
public int read(byte[] r) throws IOException{}

This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read. If it is the end of the file, -1 will be returned. It throws an IOException.

FileOutputStream 

To generate a file and enter information into it, FileOutputStream is used. If it does not already exist, the flow would generate a file before opening it for output. 

Here are two constructors that can be used to generate an object from FileOutputStream. 

To generate an input flow object to write the file, the following constructor requires a file name as a string: 

OutputStream outputStream = new FileOutputStream("C:/java/test")  

A file object is used to generate an output stream object to write the file after the constructor. First, we use the File() method to generate a file object as follows: 

File file = new File("C:/java/test"); 
OutputStream outputStream = new FileOutputStream(f); 

Once you've got OutputStream object in hand, there's a list of helpful methods that can be used to write to stream or do other stream activities. 

Method & Description
protected void finalize()throws IOException {}

This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. It throws an IOException.
public void close() throws IOException{}

This method closes the file output stream. Releases any system resources associated with the file. It throws an IOException.
public void write(byte[] w)

Writes w.length bytes from the mentioned byte array to the OutputStream.
public void write(int w)throws IOException{}

This method writes the specified byte to the output stream. It throws an IOException.

Example 

Below is the program to demonstrate InputStream and OutputStream in java: 

import java.io.*; 
public class MyFileStreamProgram { 
   public static void main(String args[]) { 
      try { 
         byte bWrite [] = {121,201,31,140,25}; 
         OutputStream os = new FileOutputStream("mytest.txt"); 
         for(int x = 0; x < bWrite.length ; x++) { 
            os.write( bWrite[x] );  
         } 
         os.close(); 
         InputStream is = new FileInputStream("mytest.txt"); 
         int size = is.available(); 
         for(int i = 0; i < size; i++) { 
            System.out.print((char)is.read() + "  "); 
         } 
         is.close(); 
      } catch (IOException e) { 
         System.out.print("Exception"); 
      } 
   } 
} 

The code above would generate the mytest.txt file and write the numbers provided in binary format. The same would be the stdout display output. 

Leave a Reply

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

Comments

protective orders in virginia

Keep sharing blogs like this one; they are quite good. You have given everyone in this blog access to a wealth of information.

Johnfrance

Thank you for your valuable information.

sam

Thank you for this wonderful article!

Belay Abera

This article was really helpful to me, thank you!

dfsdf

super article!