Java IO: Input-Output in Java
Java IO: Input-Output in Java
Java brings various Streams with its I/O package that helps the user to
perform all the input-output operations. These streams support all the types
of objects, data-types, characters, files etc to fully execute the I/O
operations.
Before exploring various input and output streams lets look at 3 standard or
default streams that Java has to provide which are also most common in
use:
1. System.in: This is the standard input stream that is used to read
characters from the keyboard or any other standard input device.
2. System.out: This is the standard output stream that is used to
produce the result of a program on an output device like the
computer screen.
3. System.err :- This is the standard output stream this at is used to
produce the error message of a program on an output device like
the computer screen.
Types of Streams:
Depending on the type of operations, streams can be divided into two
primary classes:
1. Input Stream: These streams are used to read data that must be
taken as an input from a source array or file or any peripheral
device. For eg., FileInputStream, BufferedInputStream,
ByteArrayInputStream etc.
Output Stream: These streams are used to write data as outputs into an
array or file or any output peripheral device. For eg., FileOutputStream,
BufferedOutputStream, ByteArrayOutputStream etc.
System.out.println("FileContents :");
//read characters from FileInputStream and write them
int ch;
while((ch=fin.read())!=-1)
System.out.print((char)ch);
//close the file
fin.close();
}
}
FileOutputStream in Java
FileOutputStream is an outputstream for writing data/streams of raw bytes to file or
storing data to file. FileOutputStream is a subclass of OutputStream. To write primitive
values into a file, we use FileOutputStream class. For writing byte-oriented and
character-oriented data, we can use FileOutputStream but for writing character-oriented
data, FileWriter is more preferred.
import java.io.*;
class FileExample {
public static void main(String[] args)
throws IOException
{
int i;
System.out.println("Writing successful");
//close the file
fw.flush();
fw.close();
}
}
FileReader
FileReader is useful to read data in the form of characters from a ‘text’ file.
This class inherit from the InputStreamReader Class.
The constructors of this class assume that the default character
encoding and the default byte-buffer size are appropriate. To
specify these values yourself, construct an InputStreamReader on a
FileInputStream.
FileReader is meant for reading streams of characters. For reading
streams of raw bytes, consider using a FileInputStream.
// Reading data from a file using FileReader
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
class ReadFile
{
public static void main(String[] args) throws IOException
{
// variable declaration
int ch;
Assignments
1.
System.in
System.out
Print
Println
Printf()
System.err
2.
Buffer
3.
File