logo

Java Files And I/O


Show

The java.io package encloses almost every class you might still need to carry out input and output (I/O) in Java. Entire these streams stand for an input source and an output purpose. The brook in the java.io package holds up numerous data such as prehistoric, objects, localized characters, etc.

Stream

A stream knows how to be described as a series of data. There are two types of Streams:

  • InPutStream − The InputStream is employed to read data from a source.
  • OutPutStream − The OutputStream is utilized for writing data to a destination.
streams

Java supplies sturdy but supple support for I/O concerning files and networks except for this tutorial coats very essential functionality concerning streams and I/O. We will perceive the most frequently used instances one by one −

Byte Streams

Java byte streams are utilized to do input and output of 8-bit bytes. However, several classes are narrated to byte flows but the most regularly used classes are, FileInputStream and FileOutputStream. Subsequent is an example, which makes utilize of these two classes to copy an input file into an output file −

Example

import java.io.*;
public class CopyFile {

   public static void main(String args[]) throws IOException {  
      FileInputStream in = null;
      FileOutputStream out = null;

      try {
         in = new FileInputStream("input.txt");
         out = new FileOutputStream("output.txt");
         
         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }
   }
}

Now let's have a file input.txt with the following content:

This is test for copy file.

As a subsequent step, compile the over program and carry out it, which will consequence in developing an output.txt file with the similar content as we contain in input.txt. So let us put the over code in the CopyFile.java file and do the subsequent:

$javac CopyFile.java
$java CopyFile

Character Streams

Java Byte flows are utilized to execute input and output of 8-bit bytes, while Java Character streams are utilized to execute input and output for 16-bit Unicode. However, various classes are connected to character streams but the mainly frequently used classes are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.

We can re-code the aforementioned instance, which creates the use of these two classes to copy an input file into an output file:

Example

import java.io.*;
public class CopyFile {

   public static void main(String args[]) throws IOException {
      FileReader in = null;
      FileWriter out = null;

      try {
         in = new FileReader("input.txt");
         out = new FileWriter("output.txt");
         
         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }
   }
}

Now let's have a file input.txt with the following content

This is test for copy file.

As a subsequent step, accumulate the exceeding program and perform it, which resolve result in developing output.txt file with the similar content as we have in input.txt. So let's put the aforementioned code in the CopyFile.java file and do the following −

$javac CopyFile.java
$java CopyFile

Standard Streams

Every programming languages offer to carry for typical I/O where the user's program can obtain input from a keyboard and then manufacture an output on the mainframe screen. If you are responsive to C or C++ programming languages, then you have to be conscious of three normal devices STDIN, STDOUT, and STDERR. Also, Java gives the subsequent three standard streams:

  • Standard Input − this is utilized to provide for the statistics to the user's program and typically a keyboard is adopted as a standard input stream and symbolized as System.in.
  • Standard Output − this is adopted to output the data manufactured by the user's plan and frequently a computer screen is utilized for standard output stream and symbolized as System.out.
  • Standard Error − This is utilized to output the fault data created by the user's program and regularly a computer screen is utilized for standard slipstream and stood for as System.err.

Subsequent is an easy program, which generates InputStreamReader to read standard input stream awaiting the user types a "q" −

Example

import java.io.*;
public class ReadConsole {

   public static void main(String args[]) throws IOException {
      InputStreamReader cin = null;

      try {
         cin = new InputStreamReader(System.in);
         System.out.println("Enter characters, 'q' to quit.");
         char c;
         do {
            c = (char) cin.read();
            System.out.print(c);
         } while(c != 'q');
      }finally {
         if (cin != null) {
            cin.close();
         }
      }
   }
}

Let us remain on top of code in the ReadConsole.java file and seek to compile and perform it as exposed in the subsequent program. This program goes on to read and output the identical character until we press 'Q:

$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q

Reading and Writing Files

As explained former, a stream can be classified as a series of data. The InputStream is utilized to read data from a source and the OutputStream is adopted for writing statistics to a destination.

Here is a hierarchy of classes to deal with Input and Output streams.

Files IO

The two significant flows are FileInputStream and FileOutputStream, which would be argued in this tutorial.

FileInputStream

This stream is utilized for understanding data from the folders. Objects can be developed adopting the keyword original and there are some sorts of constructors accessible.

Subsequent constructor obtains a file name as a string to generate an input stream object to convert the file:

InputStream f = new FileInputStream("C:/java/hello");

The following constructor takes a file object to create an input stream object to read the file. First, we create a file object using the File() method as follows:

File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);

Once you have the InputStream object in hand, then there is a list of helper methods that can be used to read to stream or to do other operations on the stream.

Sr.No.Method & Description
1

public void close() throws IOException{}

This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException.

2

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. Throws an IOException.

3

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.

4

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.

5

public int available() throws IOException{}

Gives the number of bytes that can be read from this file input stream. Returns an int.

There are other important input streams available, for more detail you can refer to the following links −

FileOutputStream

FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn't already exist, before opening it for output.

Here are two constructors which can be used to create a FileOutputStream object.

Following constructor takes a file name as a string to create an input stream object to write the file −

OutputStream f = new FileOutputStream("C:/java/hello")  

The following constructor takes a file object to create an output stream object to write the file. First, we create a file object using the File() method as follows:

File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);

Once you have the OutputStream object in hand, then there is a list of helper methods, which can be used to write to stream or to do other operations on the stream.

Sr.No.Method & Description
1

public void close() throws IOException{}

This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException.

2

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. Throws an IOException.

3

public void write(int w)throws IOException{}

This method writes the specified byte to the output stream.

4

public void write(byte[] w)

Writes w.length bytes from the mentioned byte array to the OutputStream.

There are other important output streams available, for more detail you can refer to the following links −

Example

Following is the example to demonstrate InputStream and OutputStream −

import java.io.*;
public class fileStreamTest {

   public static void main(String args[]) {
   
      try {
         byte bWrite [] = {11,21,3,40,5};
         OutputStream os = new FileOutputStream("test.txt");
         for(int x = 0; x < bWrite.length ; x++) {
            os.write( bWrite[x] );   // writes the bytes
         }
         os.close();
     
         InputStream is = new FileInputStream("test.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 above code would create file test.txt and would write given numbers in binary format. The same would be the output on the stdout screen.

The above code would create file test.txt and would write given numbers in binary format. The same would be the output on the stdout screen.

File Navigation and I/O

There are several other classes that we would be going through to get to know the basics of File Navigation and I/O.

Directories in Java

A directory is a File, which can hold a catalog of other directories and files. You exercise File object to produce directories, to inventory down files accessible in a directory. For total detail, make sure a list of entire the methods, which you could call on File object and what are connected to directories.

Creating Directories

There are two practical File utility techniques, which can be utilized to produce directories −

  • The mkdir( ) method generates a directory, recurring true on achievement and false on failure. Failure points to that the path particular in the File object previously exists, or that the index cannot be developed as the entire path does not exist yet.
  • The mkdirs() method generates both a listing and entire the parents of the index.

Following example creates "/tmp/user/java/bin" directory:

Example

import java.io.File;
public class CreateDir {

   public static void main(String args[]) {
      String dirname = "/tmp/user/java/bin";
      File d = new File(dirname);
      
      // Create directory now.
      d.mkdirs();
   }
}

Compile and execute the above code to create "/tmp/user/java/bin".

Note − Java automatically takes care of path separators on UNIX and Windows as per conventions. If you use a forward slash (/) on a Windows version of Java, the path will still resolve correctly.

Listing Directories

You can use the list( ) method provided by the File object to list down all the files and directories available in a directory as follows −

Example

import java.io.File;
public class ReadDir {

   public static void main(String[] args) {
      File file = null;
      String[] paths;
  
      try {      
         // create new file object
         file = new File("/tmp");

         // array of files and directory
         paths = file.list();

         // for each name in the path array
         for(String path:paths) {
            // prints filename and directory name
            System.out.println(path);
         }
      } catch (Exception e) {
         // if any error occurs
         e.printStackTrace();
      }
   }
}

This will produce the following result based on the directories and files available in your /temp directory

Output

test1.txt
test2.txt
ReadDir.java
ReadDir.class

Here at Intellinuts, we have created a complete Java tutorial for Beginners to get started in Java.