Java IO
Java IO
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a
stream because it is like a stream of water that continues to flow.
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O
system to make input and output operation in java. In general, a stream means
continuous flow of data. Streams are clean way to deal with input/output without having
every part of your code understand the physical.
In Java, 3 streams are created for us automatically. All these streams are attached with
the console.
Let's see the code to print output and an error message to the console.
1. System.out.println("simple message");
2. System.err.println("error message");
Java encapsulates Stream under java.io package. Java defines two types of streams.
They are,
1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.
Byte Stream Classes
Byte stream is defined by using two abstract class at the top of hierarchy, they are
InputStream and OutputStream.
These two abstract classes have several concrete classes that handle various devices
such as disk files, network connection etc.
DataOutputStream An output stream that contain method for writing java standard data
type
These classes define several key methods. Two most important are
These two abstract classes have several concrete classes that handle unicode
character.
Reading Characters
read() method is used with BufferedReader object to read characters. As this function
returns integer type value, we need to use typecasting to convert it into char type.
int read() throws IOException
Below is a simple example explaining character input.
class CharRead
{
public static void main( String args[])
{
BufferedReader br = new Bufferedreader(new InputstreamReader(System.in));
char c = (char)br.read(); //Reading character
}
}
Reading Strings
To read string we have to use readLine() function with BufferedReader class's object.
String readLine() throws IOException
OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an
array, peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file, an
array, peripheral device or socket.
Let's understand the working of Java OutputStream and InputStream by the figure given
below.
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 Hierarchy
InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an
input stream of bytes.
1) public abstract int read()throws reads the next byte of data from the input
IOException stream. It returns -1 at the end of the file.
3) public void close()throws IOException is used to close the current input stream.
InputStream Hierarchy
If you have to write primitive values into a file, use FileOutputStream class. You can
write byte-oriented as well as character-oriented data through FileOutputStream class.
But, for character-oriented data, it is preferred to use FileWriter than FileOutputStream.
Output:
Success...
The content of a text file testout.txt is set with the data A.
testout.txt
Output:
Success...
The content of a text file testout.txt is set with the data Welcome to javaTpoint.
testout.txt
Welcome to javaTpoint.
Note: Before running the code, a text file named as "testout.txt" is required to be
created. In this file, we are having following content:
Welcome to javatpoint.
After executing the above program, you will get a single character from the file which is
87 (in byte form). To see the text, you need to convert it into character.
Output:
Output:
Welcome to javaTpoint
For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see
the syntax for adding the buffer in an OutputStream:
1. package com.javatpoint;
2. import java.io.*;
3. public class BufferedOutputStreamExample{
4. public static void main(String args[])throws Exception{
5. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
6. BufferedOutputStream bout=new BufferedOutputStream(fout);
7. String s="Welcome to javaTpoint.";
8. byte b[]=s.getBytes();
9. bout.write(b);
10. bout.flush();
11. bout.close();
12. fout.close();
13. System.out.println("success");
14. }
15. }
Output:
Success
testout.txt
Welcome to javaTpoint.
o When the bytes from the stream are skipped or read, the internal buffer
automatically refilled from the contained input stream, many bytes at a time.
o When a BufferedInputStream is created, an internal buffer array is created.
1. package com.javatpoint;
2.
3. import java.io.*;
4. public class BufferedInputStreamExample{
5. public static void main(String args[]){
6. try{
7. FileInputStream fin=new FileInputStream("D:\\testout.txt");
8. BufferedInputStream bin=new BufferedInputStream(fin);
9. int i;
10. while((i=bin.read())!=-1){
11. System.out.print((char)i);
12. }
13. bin.close();
14. fin.close();
15. }catch(Exception e){System.out.println(e);}
16. }
17. }
Here, we are assuming that you have following data in "testout.txt" file:
javaTpoint
Output:
javaTpoint
Java application generally uses the data output stream to write data that can later be
read by a data input stream.
Java.io.DataOutputStream in Java
A data output stream lets an application write primitive Java data types to an output
stream in a portable way. An application can then use a data input stream to read
the data back in.
Implementations of some of the important methods
Program:
import java.io.*;
class DataOutputStreamDemo
{
public static void main(String args[]) throws IOException
{
//writing the data using DataOutputStream
try ( DataOutputStream dout =
new DataOutputStream(new FileOutputStream("file.dat")) )
{
dout.writeDouble(1.1);
dout.writeInt(55);
dout.writeBoolean(true);
dout.writeChar('4');
}
catch(FileNotFoundException ex)
{
System.out.println("Cannot Open the Output File");
return;
}
If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally. The Console class is
introduced since 1.5.
1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);
1. Console c=System.console();
Java Console Example
1. import java.io.Console;
2. class ReadStringTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter your name: ");
6. String n=c.readLine();
7. System.out.println("Welcome "+n);
8. }
9. }
Output
Output
Enter password:
Password is: 123
Unlike FileOutputStream class, you don't need to convert string into byte array because
it provides method to write string directly.
Java FileWriter class declaration
Let's see the declaration for Java.io.FileWriter class:
1. package com.javatpoint;
2. import java.io.FileWriter;
3. public class FileWriterExample {
4. public static void main(String args[]){
5. try{
6. FileWriter fw=new FileWriter("D:\\testout.txt");
7. fw.write("Welcome to javaTpoint.");
8. fw.close();
9. }catch(Exception e){System.out.println(e);}
10. System.out.println("Success...");
11. }
12. }
Output:
Success...
testout.txt:
Welcome to javaTpoint.
1. package com.javatpoint;
2.
3. import java.io.FileReader;
4. public class FileReaderExample {
5. public static void main(String args[])throws Exception{
6. FileReader fr=new FileReader("D:\\testout.txt");
7. int i;
8. while((i=fr.read())!=-1)
9. System.out.print((char)i);
10. fr.close();
11. }
12. }
Here, we are assuming that you have following data in "testout.txt" file:
Welcome to javaTpoint.
Output:
Welcome to javaTpoint.
Class declaration
Let's see the declaration for Java.io.BufferedWriter class:
Output:
success
testout.txt:
Welcome to javaTpoint.
1. package com.javatpoint;
2. import java.io.*;
3. public class BufferedReaderExample {
4. public static void main(String args[])throws Exception{
5. FileReader fr=new FileReader("D:\\testout.txt");
6. BufferedReader br=new BufferedReader(fr);
7.
8. int i;
9. while((i=br.read())!=-1){
10. System.out.print((char)i);
11. }
12. br.close();
13. fr.close();
14. }
15. }
Here, we are assuming that you have following data in "testout.txt" file:
Welcome to javaTpoint.
Output:
Welcome to javaTpoint.
1. package com.javatpoint;
2. import java.io.*;
3. public class BufferedReaderExample{
4. public static void main(String args[])throws Exception{
5. InputStreamReader r=new InputStreamReader(System.in);
6. BufferedReader br=new BufferedReader(r);
7. System.out.println("Enter your name");
8. String name=br.readLine();
9. System.out.println("Welcome "+name);
10. }
11. }
Output:
1. package com.javatpoint;
2. import java.io.*;
3. public class BufferedReaderExample{
4. public static void main(String args[])throws Exception{
5. InputStreamReader r=new InputStreamReader(System.in);
6. BufferedReader br=new BufferedReader(r);
7. String name="";
8. while(!name.equals("stop")){
9. System.out.println("Enter data: ");
10. name=br.readLine();
11. System.out.println("data is: "+name);
12. }
13. br.close();
14. r.close();
15. }
16. }
Output:
Java - RandomAccessFile
This class is used for reading and writing to random access file. A random access file
behaves like a large array of bytes. There is a cursor implied to the array called
file pointer, by moving the cursor we do the read write operations. If end-of-file is
reached before the desired number of byte has been read than EOFException is thrown.
It is a type of IOException.
Example
1. import java.io.IOException;
2. import java.io.RandomAccessFile;
3.
4. public class RandomAccessFileExample {
5. static final String FILEPATH ="myFile.TXT";
6. public static void main(String[] args) {
7. try {
8. System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
9. writeToFile(FILEPATH, "I love my country and my people", 31);
10. } catch (IOException e) {
11. e.printStackTrace();
12. }
13. }
14. private static byte[] readFromFile(String filePath, int position, int size)
15. throws IOException {
16. RandomAccessFile file = new RandomAccessFile(filePath, "r");
17. file.seek(position);
18. byte[] bytes = new byte[size];
19. file.read(bytes);
20. file.close();
21. return bytes;
22. }
23. private static void writeToFile(String filePath, String data, int position)
24. throws IOException {
25. RandomAccessFile file = new RandomAccessFile(filePath, "rw");
26. file.seek(position);
27. file.write(data.getBytes());
28. file.close();
29. }
30. }
The myFile.TXT contains text "This class is used for reading and writing to random
access file."