Showing posts with label java i/o classes. Show all posts
Showing posts with label java i/o classes. Show all posts

Saturday, 22 February 2020

Java I/O tutorial | I/O stream class | Java file handling - Online Help

Java I/O tutorial:

In this post, we are going to discuss Java I/O tutorial. It is also known as Java file handling. Java I/O means input and output file which we can be used to read or write in a program. So to use the I/O file then we have to import the java.io package which is used for all the file handling tasks in Java.

The main concept of the Java I/O tutorial is' 'Stream''. It is a sequence of data composed in bytes. Java defines two types of the stream:

  • byte stream 
  • character stream

The topic that we will discuss in this post is:


Java I/O tutorial - Online Help

What is Byte stream:

Byte stream handles input and output of bytes. It is defined by 2 hierarchy classes. They are the InputStream and OutputStream classes.

Each of these classes is having its own several subclasses. The most commonly used method of InputStream and OutputStream is read() and write() method, which is used to read and write bytes of data.

The InputStream and OutputStream classes are the most commonly used classes of byte stream class.


 Byte stream classes in Java:

 The important classes defined by InputStream and OutputStream are as follow:


Classes
Meaning



Input stream class
1.BufferedInputStream
Buffers input from a byte stream.
2.ByteArrayInputStream
An input stream that reads from a byte array.
3.DataInputStream
Reads the standard java datatype from a byte input stream.
4.FileInputStream
Reads binary data from a file.
5.FilterInputStream
Filters an input stream.
6.PipedInputStream
Inputs pipe.
7.SequenceInputStream
Reads sequentially one after the other.
8.PushBackInputStream
Return a byte to the input stream.




Output stream class
1.BufferedOutputStream
Buffers output to a byte stream.
2.ByteArrayOutputStream
Output streams that write a byte array
3.DataOutputStream
Writes the standard java  datatype from a byte output stream.
4.FileOutputStream
Writes binary data to a file
5.FilterOutputStream
Filters an output stream
6.PipedOutputStream
Outputs pipe
7.PrintStream
Output stream that contains print() and println()
8.PushBackOutputStream
Returns bytes to the output stream.

Methods for byte stream classes:

The important method defined by the InputStream and OutputStream classes are as follow:


Methods
Meaning



Input stream method
1.int available()
Returns the number of bytes currently  available for reading
2.int read()
Reads one byte from the input stream
3.int read(byte buf[])
Reads an array of bytes into the buffer
4.int read( byte buf[],int n,int numbytes)
Reads the number of bytes into the buffer starting from an nth byte.
5.void close()
Close the input stream.
6.void mark(int numbytes)
Places the mark at the current point in the input stream.
7.void reset()
Resets the input pointer to the previously set mark.
8.void skip()
Returns the number of bytes actually skipped.

Output stream method
1.void write(int b)
Writes the single bytes to the output stream
2.void write(byte buf[])
Writes the complete bytes in the array buffer to the output stream.
3.void close()
Closes the output stream.
4.void flush()
Clears the output buffer.

What is Character stream:

Character stream handles input and output of character. It is used to define the hierarchy of classes. They are Reader and Writer class. These classes handle the Unicode characters stream.

The two important methods of Reader and Writer class is read() and write(), which reads and writes the character data respectively

 Character stream classes in Java:

The most commonly used  subclasses of reader and writer class are listed below:


Classes
Meaning




Reader class
1.BufferedReader
Buffered input character stream.
2.CharArrayReader
Reads from a character array.
3.FileReader
An input stream that reads from a file.
4.FilterReader
Filtered reader.
5.PipedReader
Inputs pipe.
6.PushbackReader
Allows character to be refused to the input stream.
7.StringReader
Reads from a string.
8.InputStreamReader
Translates bytes to a character stream.
9.LineNumberReader
An input stream that counts lines.




Writer class
1.BufferedWriter
Buffered output character stream.
2.CharArrayWriter
Writes to a character array.
3.FileWriter
Output stream that writes to a file.
4.FilterWriter
Filtered writer.
5.PipedWriter
Output pipes.
6.StringWriter
Writes to a string.
7.OutputStreamWriter
Translates character to a byte stream.
8.PrintWriter
Output stream that contains print() and println().

Character stream methods:

The various important methods defined by The Reader and writer class is as follow:


Method
Meaning



Reader class
1.void close()
Closes the input stream.
2.int read()
Reads a character from the stream.
3.int read(char buf[])
Reads an array of character into buffer.
4.int read(char buf[],int n, int numchars)
Read the number of character into the buffer starting from the nth number.
5.void mark(int numchars[])
Places the mark at the current point in the input stream.
6.void reset()
Resets the input pointer to previously set mark.
7.void skip(long numchar)
Returns the number of character actually skipped.

Writer class
1.void write(int c)
Writes the lower 2 bytes of c to the stream.
2.void write(char buff[])
Writes the characters in the buffer to the stream.
3.void close()
Closes the output stream.

4.void flush()
Writes any buffered data that is represented by the stream.

Predefined streams in java:

All Java programs automatically import the java.lang package. This package defines a class called system which encapsulates several aspects of the Runtime environment. There are basically three types of stream consoles present in Java. They are:

  • System.in
  • System.out
  • System.err


System.out: Refers to standard output stream by default this is the console.

System.in: Refers to the standard input which is the keyboard by default.

System.err: Refers to standard error stream which also is the console by default. However, these streams may be redirected to any compatible I/O device.

System.in is an object of type InputStream. System.out and System.in is an object of type PrintSystem.

These are byte stream even though they can be used to read and write characters from one console to the other console.

Reading console input

In Java, the input console is accomplished by reading from System.in. To obtain a character-based Stream that is attached to the console, we have to wrap system.in in a BufferReader object, to create a character stream. BufferedReader supports your buffered input stream. The most commonly used constructor is:

BufferedReader(Reader inputReader)

here inputReader is the stream that is linked to the instance of BufferedReader that is being created. The reader is an abstract class. its subclass is InputStreamReader, which converts bytes to the character. To obtain an InputStreamReader object that is linked to System.in, uses the following constructor:

InputStreamReader(InputStream inputStream)

because of System.in refers to an object of the type Input system, it can be used for InputStream. Putting it all together to create a BufferedReader that is connected to the keyboard is,

BufferedReader br= new BufferedReader(new InputStreamReader(System.in))

after this stream executes, br is a character-based stream that is linked to the console through system.in

-Reading characters:

To read a character from BufferedReader, use read(). The syntax will be

int read()throw IOException

each time that read() is called, it reads a character from the input stream and returns it as an integer value. It returns -1 when the end of Stream is encountered. It can throw an IOException.

Example:
class brread
{
public static void main(String args[]) throws IOException
{
char c,
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter character,q to quit");
do{
c=(char)br.read();
System.out.println(c);
}while(c!='q');
}
}

-Reading string:

To read a string from BufferedReader, use readLine(). The general format is,

String readLine() throws IOException

each time that readLine() is called, it reads a line of text from, store each line in the array. It reads until you enter stop. It can throw an IOException.

Example:
import java.io.*;
class brread{
public static void main(String args[]) throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("enter lines of text");
System.out.println("enter stop to exit");
do
{
str=br.readLine();
System.out.println(str);
}
while(!str.Equals("stop");
}
}

Writing console output:

These methods are defined by the class PrintStream(which is the type of object reference by even though system.out). Even though System.out is a byte stream, using it for simple program output is still acceptable. For a character-based program, the method is described below.

Printstream is an output stream derived from OutpuStream. it also implements the low-level method to write(). Thus write() can be used to write to the console. The simplest form of write() defined by PrintStream is shown here,

void write(int byteval) throws IOException

This method writes to the file the bytes specified by the byteval. although the byteval is declared as an integer, only the lower level eight bits are written. Here is an example that uses write() to output the character "A" followed by the new line to the screen:

class writedemo
{
public static void main(String args[])
{
int b;
b='A';
System.out.write(b);
System.out.write('\n');
}
}

PrintWriter Class:

PrintWriter is one of the character-based classes. It displays the string equivalents of standard types(int, char, float). It has four constructors are as follows:

  • PrintWriter(Writer w)
  • PrintWriter(Writer w, boolean flushonNewline)
  • PrintWriter(OutputStream os)
  • PrintWriter(OutputStream os, boolean flushonNewline)


Here, flushOnNewline controls whether java flushes the output stream. If flushonNewLine is true, flushing automatically takes place, otherwise, flushing is not automatic.

PrintWriter supports the print() and println() method for all types including the object. To create a PrintWriter that is connected to the console output as follow:

PrintWriter pw=new PrintWriter(System.out);

The following program illustrates using a PrintWriter to handle console output:

import java.io.*;
class printwriterdemo
{
public static void main(String args[])
{
PrintWriter pw=new PrintWriter(System.out);
pw.println('x');
pw.println(400);
int i=10;
pw.println(i);
double d=4329.683596;
pw.println(d);
float f= 3.14f;
pw.println(f);
pw.println("java");
}
}


FileInputStream and FileOutputStream in java (File streams):

Java provides the number of class and method that allows you to read and write files. In Java all files are byte-oriented and Java provides methods to read and write bytes from a file to a file.

Two of the most often used stream classes are FileInputStream and FileOutputStream, which create a byte stream link to a file.

To open your file you simply create an object of one of these classes, specifying the name of the file as an argument to the constructor.

While both FileInputStream and FileOutputStream classes support constructor. The format is,

-FileInputStream(String filename) throws FileNotFoundException

-FileOutputStream(String filename)throws FileNotFoundException

here, filename specified the name of the file that you want to open. when you create an input stream if the file doesn't exist then FileNotFoundException is thrown. For output stream, if the file cannot be created then FileNotFoundException has thrown. When an output file is open any pre-existing file by the same name is destroyed.

When you are done with the file you should close it by calling close() method it is defined by both as FileInputStream and FileOutputStream as shown here:

void close() throws IOException

To read a file, you can use the read() method that is defined within FileInputStream. The general form is,

int read() throws IOException

Each time the read() is called it reads a single byte from the file and returns the byte as an integer value, read() returns -1 when the end of file is encountered. It can throw an IOException.

The following program uses read() to input and displays the content of the text file. The name of which is specified as a command-line argument.

Note the try-catch block that handles the two errors that might occur when this program is used- the specified file not being found or the user forgetting to include the name of the file.

You can use this same approach whenever you use common line arguments.

import java.io.*;
class showfile
{
public static void main(String args[]) throws IOException
{
int i;
FileInputStream fin;
try
{
fin=new FileInputStream(args[0])'
}
catch(FileNotFoundException e)
{
System.out.println("file not found");
return;
}
catch(ArrayIndexOutOfBoundException e)
{
System.out.println("usage: showfile file");
return;
}
do
{
}
while(i!=-1)'
}
}