Java Basic Input and Output


JAVA Basic Input and Output

Below are some basic and important notes on File input/output through Java Programming.

  • In Java, I/O Streams are a powerful concept that simplifies I/O Operations.
  • An I/O Stream represents an input source or output destination.
  • Java programs uses an input stream to read data from a source, one item at a time.
  • output stream is used to write data to a destination, one item at a time.

Below are the types of I/O stream available in Java. All the below classes are defined in java.io package

Byte Streams – perform input and output of 8-bit bytes.
Character Streams – handle I/O of character data, automatically handling translation to and from the local character set.
Buffered Streams – optimizes input and output by reducing the number of calls to the native API.
Scanning and Formatting – allows a program to read and write the formatted text.
I/O from the Command Line – describes the Standard Streams and the Console objects.
Data Streams – handle binary I/O of primitive data types and String values.
Object Streams – handle binary I/O of objects.

Byte Streams

All Byte Streams are sub classes of InputStream and OutputStream classes. out of them, for file I/O operations, Important ones are – FileInputStream and FileOutputStream.

Sample Byte stream I/O program is shown below.

  • To avoid resource leaks, programmer must close a stream when it is no longer needed.
Character streams

Character stream classes automatically translates Unicode conventions to and from Local Character set. All Character Stream classes extend Reader and Writer classes. Specialized Character Stream classes for File I/O are – FileReader and FileWriter classes.

Sample File I/O by character stream classes is shown in below program.

Buffered Streams
  • Each read or write request in un-buffered I/O, is directly handled by underlying OS, resulting in less efficiency, frequent disk/file access is relatively expensive.
  • But in Buffered I/O, a separate memory area is maintained as a buffer. Buffered input streams read data from buffer until it is empty and the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.
  • One can convert un-buffered streams into buffered streams by wrapping the un-buffered stream object into the constructor for a buffered stream class.

reader = new BufferedReader(new FileReader(“sampleinput.txt”));
writer = new BufferedWriter(new FileWriter(“sampleoutput3.txt”));

  • There are four buffered stream classes used to wrap un-buffered streams: BufferedInputStream and BufferedOutputStream create buffered byte streams, while BufferedReader and BufferedWriter create buffered character streams.

Sample File I/O program by Buffered streams is shown below.

  • An auto flush PrintWriter object flushes the buffer on every invocation of println().
Scanning and Formatting
  • Scanning and Formatting classes are useful for converting to and from neatly formatted data items.
  • The scanner API breaks input into individual tokens and translates individual tokens according to their data type.
  • Scanner uses white space as a token separator by default. (White space characters include blanks, tabs, and line terminators).
  • To use different token separator, useDelimiter() method with a regular expression can be invoked on a Scanner object. To use “comma followed by space” as delimiter, we can invoke the method as

in.useDelimiter(“,\\s*”);

Sample File I/O program by Scanner API is shown below.

and its output would be as shown below:

  • The formatting API assembles data into nicely formatted, human-readable form.
  • Formatting stream objects are instances of either PrintWriter, a character stream class, or PrintStream, a byte stream class
  • The format () method formats multiple arguments based on a format string. The format string consists of static text embedded with format specifiers; except for the format specifiers, the format string is output unchanged.

Example:

int i = 2;
double r = Math.sqrt(i);
System.out.format(“The square root of %d is %f. %n”, i, r);  

// here %n for new line.

O/p: The square root of 2 is 1.414214.

System.out.format(“%f, %1$+020.10f %n”, Math.PI);

O/p: 3.141593, +00000003.1415926536

I/O from the Command Line
  • The Java platform supports three Standard Streams: Standard Input, accessed through System.in; Standard Output, accessed through System.out; and Standard Error, accessed through System.err.
  • These objects are defined automatically and do not need to be opened. These are byte streams and defined as PrintStream objects.
  • To read console input, you first construct a Scanner that is attached to System.in :

Scanner in = new Scanner(System.in);

  • Various methods of the Scanner class to read input. For example, the nextLine() method reads a line of input.

System.out.print(“What is your name? “);
String name = in.nextLine();

nextLine() method accepts input that might contain spaces as well.

To read a single word (delimited by whitespace), call next()

String firstName = in.next();

To read an integer, use the nextInt() method.

System.out.print(“How old are you? “);
int age = in.nextInt();

Similarly, the nextDouble method reads the next floating-point number.

We can print a number x to the console with the statement System.out.print(x).
System.out.printf(“%8.2f”, x);

We can supply multiple parameters to printf . For example:

System.out.printf(“Hello, %s. Next year, you’ll be %d”, name, age);

  • A more advanced alternative to the Standard Streams is the Console. This is a single, predefined object of type Console. Retrieve the Console object by invoking System.console().

Console c = System.console();
String login = c.readLine(“Enter your login: “);
char [] oldPassword = c.readPassword(“Enter your old password: “);

Invoke Console.readLine() to prompt for and read the user response.
Invoke Console.readPassword() to prompt for and read the user’s password.


Profile photo of Siva

About Siva

Senior Hadoop developer with 4 years of experience in designing and architecture solutions for the Big Data domain and has been involved with several complex engagements. Technical strengths include Hadoop, YARN, Mapreduce, Hive, Sqoop, Flume, Pig, HBase, Phoenix, Oozie, Falcon, Kafka, Storm, Spark, MySQL and Java.

Leave a comment

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