Java I/O Basics: Streams and File Handling
Java I/O Basics: Streams and File Handling
Java I/O (Input and Output) is used to process the input and produce the output.
Java Input
There are several ways to get input from the user in Java. To get input by using
Scanner object, import Scanner class using:
import [Link];
Then, we will create an object of Scanner class which will be used to get input from the user.
Scanner input = new Scanner ([Link]);
int number = [Link](); Example : Get Integer Input From the User
import [Link];
class Input{
public static void main(String[] args){ Scanner input =newScanner ([Link]); [Link]
("Enter an integer: "); int number =[Link] ();
[Link] ("You entered”+ number);
}
}
Output
Enter an integer: 23
You entered 23
Java Output
Simply use [Link](), [Link]() or [Link]() to send output to
standard output (screen).system is a class and out is a public static field which accepts
output data.
5.1
U23CS302-Object Oriented Programming using JAVA UNIT – V
class Test
{
public static void main(String[] args)
{
[Link]("Java programming is interesting.");
}
}
Output:
Java programming is interesting.
What's the difference between println (), print () and printf ()?
print () - prints string inside the quotes.
println () - prints string inside the quotes similar like print() method. Then the cursor
moves to the beginning of the next line.
printf () - it provides string formatting.
4.1.1: STREAMS
PREDEFINED STREAMS:
In java, 3 streams are created for us automatically. All these streams are attached with console.
1) [Link]: This is used to feed the data to user's program and usually a keyboard is used as
standard input stream and represented as [Link]. – It is an object of type InputStream.
2) [Link]: This is used to output the data produced by the user's program and usually a
computer screen is used to standard output stream and represented as [Link]. - It is an object
of type PrintStream
3) [Link]: This is used to output the error data produced by the user's program and usually
a computer screen is used to standard error stream and represented as [Link]. - It is an object
of type PrintStream
TYPES OF STREAMS:
1. Byte Stream – Byte Streams provide a convenient means of handling input and output
in terms of bytes. Byte streams are used when reading or writing binary data.
2. Character Stream – Character streams provide a convenient means of handling input or output
5.2
U23CS302-Object Oriented Programming using JAVA UNIT – V
in terms of characters. In some cases, character streams are more efficient than byte streams.
OutputStream
Java application uses an output stream to write data to a destination, it may be a file, an array,
peripheral device or socket.
5.3
U23CS302-Object Oriented Programming using JAVA UNIT – V
InputStream
Java application uses an input stream to read data from a source, it may be a file, an array,
peripheral device or socket.
OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some sink.
4) public void close()throws IOException is used to close the current output stream.
OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some sink.
5.4
U23CS302-Object Oriented Programming using JAVA UNIT – V
Method Description
1. public void write(int)throws IOException is used to write a byte to the current output
stream.
2. public void write(byte[])throws IOException is used to write an array of byte to the
current output stream.
3. public void flush()throws IOException flushes the current output stream.
4. public void close()throws IOException is used to close the current output stream.
InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing
an input stream of bytes.
Commonly used methods of InputStream class
Method Description
1) public abstract int read() throws IOException reads the next byte of data from the input
[Link] returns -1 at the end of file.
2) public int available() throws IOException returns an estimate of the number of bytes
that can be read from the current input stream.
3) public void close()throws IOException is used to close the current input stream.
FileOutputStream class
Java FileOutputStream is an output stream for writing data to a file.
If you have to write primitive values then use FileOutputStream. Instead, for character-oriented
data, prefer FileWriter. But you can write byte-oriented as well as character-oriented data.
Method Description
protected void finalize() It is used to clean up the connection with the file output stream.
void write(byte[] ary) It is used to write [Link] bytes from the byte array to the file
output stream.
void write(byte[] ary, int off, It is used to write len bytes from the byte array starting at offset off to
int len) the file output stream.
void write(int b) It is used to write the specified byte to the file output stream.
5.5
U23CS302-Object Oriented Programming using JAVA UNIT – V
Output: success...
FileInputStream class
Java FileInputStream class obtains input bytes from a [Link] is used for reading streams of raw
bytes such as image data. For reading streams of characters, consider using FileReader.
It should be used to read byte-oriented data for example to read image, audio, video etc
.
Method Description
int available() It is used to return the estimated number of bytes that can
be read from the input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to [Link] bytes of data from the
input stream.
int read(byte[] b, int off, It is used to read up to len bytes of data from the input
int len) stream.
long skip(long x) It is used to skip over and discards x bytes of data from the
input stream.
protected void finalize() It is used to ensure that the close method is call when
there is no more reference to the file input stream.
void close() It is used to closes the stream.
5.6
U23CS302-Object Oriented Programming using JAVA UNIT – V
9. }
10. [Link]();
11. }catch(Exception e){[Link](e);}
12. }
13. }
Constructor Description
BufferedOutputStream(Output It creates the new buffered output stream which is used for
Stream os) writing the data to the specified output stream.
BufferedOutputStream(Output It creates the new buffered output stream which is used for
Stream os, int size) writing the data to the specified output stream with a specified
buffer size.
Method Description
void write(int b) It writes the specified byte to the buffered output stream.
void write(byte[] b, int off, int It write the bytes from the specified byte-input stream into a
len) specified byte array, starting with the given offset
void flush() It flushes the buffered output stream.
In this example, we are writing the textual information in the BufferedOutputStream object
which is connected to the FileOutputStream object. The flush() flushes the data of one stream
and send it into another. It is required if you have connected the one stream with another.
1. import [Link].*;
2. class Test{
3. public static void main(String args[])throws Exception{
4. FileOutputStream fout=new FileOutputStream("[Link]");
5. BufferedOutputStream bout=new BufferedOutputStream(fout);
6. String s="Java is my favourite language";
7. byte b[]=[Link]();
8. [Link](b);
9. [Link]();
10. [Link]();
11. [Link]();
12. [Link]("success");
13. }
14. }
Output: success...
5.7
U23CS302-Object Oriented Programming using JAVA UNIT – V
Constructor Description
BufferedInputStream(InputStream It creates the BufferedInputStream and saves it argument,
IS) the input stream IS, for later use.
BufferedInputStream(InputStream It creates the BufferedInputStream with a specified buffer
IS, int size) size and saves it argument, the input stream IS, for later
use.
BufferedInputStream class
Java BufferedInputStream class is used to read information from stream. It internally uses
buffer mechanism to make the performance fast.
Method Description
int available() It returns an estimate number of bytes that can be read from the input
stream without blocking by the next invocation method for the input
stream.
int read() It read the next byte of data from the input stream.
int read(byte[] b, int off, int It read the bytes from the specified byte-input stream into a specified
ln) byte array, starting with the given offset.
void close() It closes the input stream and releases any of the system resources
associated with the stream.
void reset() It repositions the stream at a position the mark method was last called
on this input stream.
void mark(int readlimit) It sees the general contract of the mark method for the input stream.
long skip(long x) It skips over and discards x bytes of data from the input stream.
boolean markSupported() It tests for the input stream to support the mark and reset methods.
1. import [Link].*;
2. class SimpleRead{
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("[Link]");
6. BufferedInputStream bin=new BufferedInputStream(fin);
7. int i;
8. while((i=[Link]())!=-1){
9. [Link]((char)i);
10. }
11. [Link]();
12. [Link]();
5.8
U23CS302-Object Oriented Programming using JAVA UNIT – V
DataInputStream class
DataInputStream class allows the programmer to read primitive data from the input source.
Method Description
int read(byte[] b) It is used to read the number of bytes from the input stream.
int readInt() It is used to read input bytes and return an int value.
byte readByte() It is used to read and return the one input byte.
char readChar() It is used to read two input bytes and returns a char value.
double readDouble() It is used to read eight input bytes and returns a double value.
boolean readBoolean() It is used to read one input byte and return true if byte is non zero,
false if byte is zero.
int skipBytes(int x) It is used to skip over x bytes of data from the input stream.
void readFully(byte[] b) It is used to read bytes from the input stream and store them into the
buffer array.
void readFully(byte[] b, int off, It is used to read len bytes from the input stream.
int len)
DataOutputStream class
The DataOutputStream stream let you write the primitives to an output source. Example:
Following is the example to demonstrate DataInputStream and DataInputStream. This example
reads 5 lines given in a file [Link] and converts those lines into capital letters and finally copies
them into another file [Link].
Method Description
int size() It is used to return the number of bytes written to the data output
stream.
void write(int b) It is used to write the specified byte to the underlying output
stream.
void writeChar(int v) It is used to write char to the output stream as a 2-byte value.
5.9
U23CS302-Object Oriented Programming using JAVA UNIT – V
void writeByte(int v) It is used to write a byte to the output stream as a 1-byte value.
[Link]
this is test 1 , this is test 2 , this is test 3 , this is test 4 , this is test 5 ,
[Link]
import [Link].*;
public class Test{
public static void main(String args[])throws IOException{
DataInputStream d = new DataInputStream(new FileInputStream("[Link]")); DataOutputStream
out = new DataOutputStream(new FileOutputStream("[Link]")); String count;
while((count = [Link]()) != null){ String u = [Link](); [Link](u);
[Link](u + " ,");}
[Link]();
[Link]();
}}
Output:
THIS IS TEST 1 , THIS IS TEST 2 , THIS IS TEST 3 , THIS IS TEST 4 , THIS IS TEST 5 ,
4. PrintStream
The PrintStream class provides methods to write data to another stream. The PrintStream class
automatically flushes the data so there is no need to call flush() method. Moreover, its methods
don't throw IOException.
There are many methods in PrintStream class. Let's see commonly used methods of
PrintStream class:
public void print(boolean b): it prints the specified boolean value.
public void print(char c): it prints the specified char value.
public void print(char[] c): it prints the specified character array values.
public void print(int i): it prints the specified int value.
public void print(long l): it prints the specified long value.
public void print(float f): it prints the specified float value.
public void print(double d): it prints the specified double value.
public void print(String s): it prints the specified string value.
public void print(Object obj): it prints the specified object value.
5.10
U23CS302-Object Oriented Programming using JAVA UNIT – V
public void println(boolean b): it prints the specified boolean value and terminates the
line.
public void println(char c): it prints the specified char value and terminates the line.
public void println(char[] c): it prints the specified character array values and terminates the
line.
public void println(int i): it prints the specified int value and terminates the
line.
public void println(long l): it prints the specified long value and terminates the line.
public void println(float f): it prints the specified float value and terminates the
line.
public void println(double d): it prints the specified double value and terminates the
line.
public void println(String s): it prints the specified string value and terminates the line./li>
public void println(Object obj): it prints the specified object value and
terminates the line.
public void println(): it terminates the line only.
public void printf(Object format, Object... args): it writes the formatted string to the
current stream.
public void printf(Locale l, Object format, Object... args): it writes the formatted
string to the current stream.
public void format(Object format, Object... args): it writes the formatted string
to the current stream using specified format.
public void format(Locale l, Object format, Object... args): it writes the formatted
string to the current stream using specified format.
5.11
U23CS302-Object Oriented Programming using JAVA UNIT – V
Reader class:
The [Link] class is a abstract class for writing to character streams.
Writer class:
The [Link] class is a abstract class for writing to character streams
Methods defined by Writer class:
Method Description
This methodappends the specified
Writer append(char ch) character to this writer.
This methodappends the specified
Writer append(CharSequence chars) character sequence to this writer.
Writer append(CharSequence chars, int begin, This methodappends the specified
int end) character sequence to this writer.
This method loses the stream, flushing it first.
abstract void close()
abstract void flush() This method flushes the stream.
void write(int ch) This method writes a single character.
void write(char buffer[]) This method writes an array of characters.
Constructor Description
FileWriter(String file) creates a new file. It gets file name in string.
FileWriter(File file) creates a new file. It gets file name in File object.
5.12
U23CS302-Object Oriented Programming using JAVA UNIT – V
Constructor Description
FileReader(String file) It gets filename in string. It opens the given file in read mode. If file
doesn't exist, it throws FileNotFoundException.
FileReader(File file) It gets filename in file instance. It opens the given file in read mode.
If file doesn't exist, it throws FileNotFoundException.
Method Description
public int read() returns a character in ASCII form. It returns -1 at the end of file.
public void close() closes FileReader.
Constructors
BufferedWriter bw = new BufferedWriter(writer w) BufferedWriter bw = new
BufferedWriter(writer r, int size)
BufferedWriter never communicates directly with the file. It should be communicate through
some writer object only.
BufferedReader
BufferedReader class can read character data from the file.
Constructors
1. BufferedReader br = new BufferedReader(Reader r)
2. BufferedReader br = new BufferedReader(Reader r, int buffersize)
3. BufferedReader never communicates directly with the file. It should Communicate through
some reader object only.
5.13
U23CS302-Object Oriented Programming using JAVA UNIT – V
OutputStreamWriter
OutputStreamWriter behaves as a bridge to transfer data from character stream to byte stream. It
uses default charset or we can specify charset for change in character stream to byte
stream.
Constructors
1. OutputStreamWriter(OutputStream out)
2. OutputStreamWriter(OutputStream out, Charset cs)
3. OutputStreamWriter(OutputStream out, CharsetEncoder enc)
4. OutputStreamWriter(OutputStream out, String charsetName)
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
public class OutputStreamWriterDemo {
public static void main(String[] args) {
5.14
U23CS302-Object Oriented Programming using JAVA UNIT – V
Output
Hello World!
This is OutputStreamWriter Code Example.
InputStreamReader
InputStreamReader behaves as bridge from bytes stream to character stream. It also uses charset
to decode byte stream into character stream.
Constructors
1. InputStreamReader(InputStream in_strm)
2. InputStreamReader(InputStream in_strm, Charset cs)
3. InputStreamReader(InputStream in_strm, CharsetDecoder dec)
4. InputStreamReader(InputStream in_strm, String charsetName)
5.15
U23CS302-Object Oriented Programming using JAVA UNIT – V
[Link]();
}
[Link]("you entered "+a+" and "+b); }}
Output
Enter a number..
10
Enter another number..
14
you entered 10 and 14
4. PrintWriter Class
The [Link] class prints formatted representations of objects to a text- output
stream.
PrintWriter defines several constructors. The one we will use is shown here:
PrintWriter(OutputStream outputStream, boolean flushOnNewline)
Here, outputStream is an object of type OutputStream, and flushOnNewline controls whether
Java flushes the output stream every time a newline ('\\n') character is output. If flushOnNewline
is true, flushing automatically takes place. If false, flushing is not automatic.
PrintWriter supports the print( ) and println( ) methods for all types including Object.
Thus, you can use these methods in the same way as they have been used with [Link]. If
an argument is not a simple type, the PrintWriter methods call the object's toString( )
method and then print the result.
To write to the console by using a PrintWriter, specify [Link] for the output stream
and flush the stream after each newline. For example, this line of code creates a PrintWriter
that is connected to console output:
PrintWriter pw = new PrintWriter([Link], true);
5.16
U23CS302-Object Oriented Programming using JAVA UNIT – V
The Java Console class is be used to get input from console. It provides methods to read texts
and passwords.
If you read password using Console class, it will not be displayed to the user. The
[Link] class is attached with system console internally.
1. String text=[Link]().readLine();
2. [Link]("Text is: "+text);
Method Description
It is used to retrieve the reader object associated with the
Reader reader() console
String readLine(String fmt, Object... It provides a formatted prompt then reads the single line of
args) text from the console.
char[] readPassword(String fmt, It provides a formatted prompt then reads the password that
Object... args) is not being displayed on the console.
Console format(String fmt, Object... It is used to write a formatted string to the console output
args) stream.
Console printf(String format, Object... It is used to write a string to the console output stream.
args)
System class provides a static method console() that returns the singleton instance of
Console class.
public static Console console(){}
5.17
U23CS302-Object Oriented Programming using JAVA UNIT – V
1. import [Link];
2. class ReadStringTest{
3. public static void main(String args[]){
4. Console c=[Link]();
5. [Link]("Enter your name: ");
6. String n=[Link]();
7. [Link]("Welcome "+n);
8. }
9. }
Output
Output
For example:
1)import [Link] // Import the File class
2)File obj = new File("[Link]"); // Specify the filename
3)
4)
The File class has many useful methods for creating and getting information about files.
For example:
5.18
U23CS302-Object Oriented Programming using JAVA UNIT – V
1) Create a File
To create a file in Java, you can use the createNewFile() method. This method returns a boolean
value: true if the file was successfully created, and false if the file already exists.
Example:
import [Link];
import [Link];
public class CreateFile {
public static void main(String[] args) {
try {
File myObj = new File("[Link]");
if ([Link]()) {
[Link]("File created: " + [Link]());
} else {
[Link]("File already exists.");
}
} catch (IOException e) { [Link]("An error occurred."); [Link]();
}
}
}
5.19
U23CS302-Object Oriented Programming using JAVA UNIT – V
2) Write To a File
In the following example, we use the FileWriter class together with its write() method to write
some text to the file we created in the example above. Note that when we are done writing to the
file, we should close it with the close() method:
Example:
import [Link]; // Import the FileWriter class
import [Link]; // Import the IOException class to handle errors public class
WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("[Link]"); [Link]("Files in Java might be
tricky, but it is fun enough!"); [Link]();
3) Read a File
In the following example, we use the Scanner class to read the contents of the text file we
created in the previous example:
Example:
import [Link]; // Import the File class
import [Link]; // Import this class to handle errors import
[Link]; // Import the Scanner class to read text files
5.20
U23CS302-Object Oriented Programming using JAVA UNIT – V
5.21