Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Learn about Java Input / Output

In this article we will learn about the basic concepts of Input/output handling in java with both console and file.

Differences between Input and Output

Input can be termed as any information that is required by a program to execute. Input can be provided in many forms to a program. Some programs may use some visual components like a dialog box to accept and return the character string that is typed by the user.Still other programs, like word processing, get some of their input from a file that is stored on the computer's hard disk drive or any other device.

Output can be termed as any information that the program must present to the user. When we execute any program on our computer, the information which we see on our computer screen is output.

To perform input/output operations in java there is a package java.io that contains most of the classes to perform input and output operations.

A stream can be defined as a sequence of data. There are 2 types of streams available.

  1. Input Stream: used to read data from a source.
  2. OutputStream: used for writing data to a destination.

In this article we will discuss the ways of input and output in java with both console and file.

  1. Console Input
  2. Console Output
  3. File Input
  4. File Output

Console input

Console input is any input that is entered in the console window instead of typing it into any dialog or interactive window.

Note: Console window is automatically launched when we run a java program (non GUI).

When user types any information in console, there are many java I/O classes that take care of handling the input/output. The java.io and java.util packages contain most of the classes that are uses for I/O purpose.The following two classes are the most important classes that are widely use in java programs.

  1. Java.io.InputStream - This class stores information about the connection between an input device and the program.
  2. Java.util.Scanner – this class is used to read the input available from an InputStream object.

The Scanner class has a method called nextLine that returns a line of text as typed by the user.For console input, the Scanner class takes an argument as instance of an InputStream object.

Steps to use scanner class in console input

  1. Use the System.in object to create a Scanner object.
    Scanner scanner = new Scanner ( System.in );
  2. Display a prompt to the user to type some data.
    System.out.print(“Type some data for the program: " );
  3. Use the Scanner object to read a line of text from the user.
    String input = scanner.nextLine();
  4. Display the input received from the user.
     System.out.println( "input = " + input );

To use the Scanner class in java we must import the java.util.Scanner.

Listing 1. Console input using class Scanner: Java program that demonstrates console based input and output.

import java.util.Scanner;  
  public class ScannerInputClass 
  {
       private static Scanner scanner = new Scanner( System.in );
       public static void main ( String [] args )
       {
             // Prompt the user to type some data
             System.out.print( "Type some data: " );
                      
            // Read a line of text from the user.
           String input = scanner.nextLine();
           // Display the input back to the user.
          System.out.println( "input = " + input );
   
      } // end main method
   } // end ScannerInputClass class

Output: Type some data: Test Console

Input = Test Console

Explanation Listing 1 : Here we use scanner class to take input from the user and display the output.

Here the method nextLine of scanner class returns the string object of input. Suppose the user types “111” then nextLine will return the object as String, not integer. On receiving the string object , the user will have to convert this string object to integer object using parseInt. Like:

  1. Get a String of characters that is in an integer format, e.g., "123".
    String input = scanner.nextLine
  2. Use the Integer class to parse the string of characters into an integer.
    int number = Integer.parseInt( input ); 

But the Scanner class have other ways to do the same thing, instead of converting the string object into integer using parseInt , it has another method nextInt that returns the integer object.

nextInt() reads the next available input as an int value.

int number = scanner.nextInt();  // from console input example above.

There are several other methods of Scanner class that use to read double , float values too.

Console Output

What we are watching on console can be termed as console output. We have used system.out.print(...) and System.out.println(...) statements for displaying simple text messages to the user. The System.out object is an instance of the PrintStream class, which is a type of OutputStream.

A stream object is used to store information needed to connect a computer program to an input or output device. There is a PrintStream object that adds functionality to output streams. The PrintStream class extends the OutputStream class and contains definitions for all of the versions of the print and println methods that we use to display information .

Console output in Java is very easy because the print and println methods will work with any type of data.

The java.lang.System class creates three different I/O streams automatically for us when our application begins execution. Each of these streams is public and static so that we can access them directly without having to create an instance of the System class.

  • System.in - InputStream object named System.in that uses in console input.
  • System.out – PrintStream object uses to display information on screen, where PrintScreen is type of OutputStream
  • System.err- this object is also an instance of the PrintStream class and is available for use in displaying information to the computer screen.

For example, if the following variables are defined,

    int x = 3;
      double rate = 5.5;

they can all be printed using print or println as follows:

    System.out.print( "x = " + x );
      System.out.println( rate );

We can also print other types of data, including other objects, using the print and println methods.

File Input

As we have discussed that data can be read from a variety of different sources, including data files stored on devices such as hard disk drives or any other drives.To read and write from external files, these files will need to be opened and a Scanner will be attached to the file object. The process is actually very similar to the console input.

Note: The main difference is that the Scanner will be created from a File object instead of an InputStream object in case of file input.

As we know java.io package contains lots of classes that perform input/output in java. There is File class that is needed to do input output operations on files. Java.io.file stores information about a file on a computer drive.

The basic thing that must be taken into consideration is to make use of exception handling. In File input, file may not be present on hard disk for which we are ready to read the information so we must inform the compiler that we are calling a method that may cause a checked exception to occur. Creating a Scanner object from a File object may cause a FileNotFoundException. Here's a code reading a text file.

Listing 2. File input using class File

import java.util.Scanner;  
  Import java.io.*;
  public class FileInputClass 
   {
       public static void main ( String [] args )
      {
         System.out.print( "Enter the filename: " );  
      String fileName = scanner.nextLine();             
    File file = new File( fileName );
                                 
     if ( file.exists() )                          
     Scanner inFile = new Scanner( file );
     int lineNum = 0;
     while ( inFile.hasNext() )
      {
         line = inFile.nextLine();   // read the next line
 
         // Output the line read to the screen for the user
         System.out.println( ++lineNum + ": " + line );
      }
      // When we're done reading the file,
      // close the Scanner object attached to the file
      inFile.close();
    }                   
}

Note:

  • Don't forget to add import java.io.* (as well as java.util.* for the Scanner class).
  • Close the File object when you're done reading data from the file.

File Output

Writing data to a file is similar to writing data to the screen. You will open a file for writing and then print to that file any data that you would like to store there. You must remember to close the file or risk having some data not be written and saved to the file. We will use of the java.io.PrintStream for file output.

When you intend to write data to a file, you should consider what is the appropriate action to take if the file already exists.The exists method of the File class will return true if the file already exists.

Here's an example file output:

Listing 3. File output using PrintStream

import java.util.Scanner;  
  Import java.io.*;
  public class FileOutputClass 
   {
       public static void main ( String [] args )
      {
   
     // Create a PrintStream attached to a file named "output.txt".
   // This will overwrite the file if it already exists
   PrintStream ps = new  PrintStream( "output.txt" );
 
   // Buffer some data to write to the file (doesn't actually write until flush)
   ps.print( "Some test data that will be written when flush is called.");
        
  // Flush all buffered data to the file.
  ps.flush();
  // Buffer some more data.
  ps.println( “Another set of data” );
 
  // Close the file (by closing the PrintStream).  
  // Also flushes any remaining buffered output.
  ps.close();
 }
}

Conclusion

Input and output handling in java revolves around two major packages: java.io.* and java.util.*.These two packages contain almost all the necessary classes to handle input/output operations in java. The above example contains the techniques of performing input and output operations in java.



Have experience over java, c++ c#, web-development, android development.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login