File Handling in Java
File Handling in Java
In this tutorial, we will learn about Java File and its various operations
with the help of examples.
Here, we have created a file object named file. The object can be used
to work with files and directories.
Note: In Java, creating a file object does not mean creating a file.
Instead, a file object is an abstract representation of the file or directory
pathname (specified in the parenthesis).
import java.io.*;
class Main {
public static void main(String[] args) {
try {
In the above example, we have created a file object named file. The file
object is linked with the specified file path.
Here, we have used the file object to create the new file with the
specified path.
class Main {
public static void main(String[] args) {
// Reads characters
input.read(array);
System.out.println("Data in the file:");
System.out.println(array);
Output
To read the data from the input.txt file, we have used the read() method
of FileReader.
class Main {
public static void main(String args[]) {
Output
We can use the delete() method of the File class to delete the specified
file or directory. It returns
true if the file is deleted.
false if the file does not exist.
import java.io.File;
class Main {
public static void main(String[] args) {
Output
In the above example, we have created an object of File named file. The
file now holds the information about the specified file.
Here we have used the delete() method to delete the file specified by
the object.
Input-OutputStream : FileInput/OutputStream, BufferedInput/OutputStream,
DataInput/OutputStream
Reader-Writer : FileReader/Writer, BufferedReader/Writer, InputStreamReader,
OutputStreamWriter
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.
1. System.out.println("simple message");
2. System.err.println("error message");
OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given
below:
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.
Method Description
OutputStream Hierarchy
InputStream class
InputStream class is an abstract class. It is the superclass of all classes
representing an input stream of bytes.
Method Description
1) public abstract int reads the next byte of data from the input strea
read()throws IOException returns -1 at the end of the file.
InputStream Hierarchy
import java.io.FileInputStream;
try {
FileInputStream input = new FileInputStream("input.txt");
catch(Exception e) {
e.getStackTrace();
}
}
}
import java.io.FileOutputStream;
try {
FileOutputStream output = new
FileOutputStream("output.txt");
byte[] array = data.getBytes();
output.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}
Constructor Description
Method Description
void write(int b) It writes the specified byte to the buffered output stream.
void write(byte[] b, It write the bytes from the specified byte-input stream i
int off, int len) specified byte array, starting with the given offset
1. package com.javatpoint;
2. import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
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.
Constructor Description
Method Description
int available() It returns an estimate number of bytes that can be read from
input stream without blocking by the next invocation metho
the input stream.
int read() It read the next byte of data from the input stream.
int read(byte[] b, It read the bytes from the specified byte-input stream i
int off, int ln) specified byte array, starting with the given offset.
void close() It closes the input stream and releases any of the sy
resources associated with the stream.
void mark(int It sees the general contract of the mark method for the
readlimit) stream.
long skip(long x) It skips over and discards x bytes of data from the input stre
boolean It tests for the input stream to support the mark and
markSupported() methods.
package com.javatpoint;
1.
2. import java.io.*;
3. public class BufferedInputStreamExample{
4. public static void main(String args[]){
5. try{
6. FileInputStream fin=new FileInputStream("D:\\testout.txt");
7. BufferedInputStream bin=new BufferedInputStream(fin);
8. int i;
9. while((i=bin.read())!=-1){
10. System.out.print((char)i);
11. }
12. bin.close();
13. fin.close();
14. }catch(Exception e){System.out.println(e);}
15. }
16. }
javaTpoint
Output:
javaTpoint
Java DataOutputStream Class
Java DataOutputStream class allows an application to write
primitive Java data types to the output stream in a machine-
independent way.
Java application generally uses the data output stream to write data
that can later be read by a data input stream.
Method Description
void write(byte[] b, int off, It is used to write len bytes of data to the output strea
int len)
void writeUTF(String str) It is used to write a string to the output stream using U
encoding in portable manner.
1. package com.javatpoint;
2.
3. import java.io.*;
4. public class OutputExample {
5. public static void main(String[] args) throws IOException {
6. FileOutputStream file = new FileOutputStream(“D:\\testout.txt”);
7. DataOutputStream data = new DataOutputStream(file);
8. data.writeInt(65);
9. data.flush();
10. data.close();
11. System.out.println("Succcess...");
12. }
13. }
Output:
Succcess...
testout.txt:
Java application generally uses the data output stream to write data
that can later be read by a data input stream.
Method Description
int read(byte[] b, int off, int It is used to read len bytes of data from the input str
len)
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
value.
boolean readBoolean() It is used to read one input byte and return true if b
non zero, false if byte is zero.
String readUTF() It is used to read a string that has been encoded usin
UTF-8 format.
void readFully(byte[] b) It is used to read bytes from the input stream and
them into the buffer array.
void readFully(byte[] b, int It is used to read len bytes from the input stream.
off, int len)
1. package com.javatpoint;
2. import java.io.*;
3. public class DataStreamExample {
4. public static void main(String[] args) throws IOException {
5. InputStream input = new FileInputStream("D:\\testout.txt");
6. DataInputStream inst = new DataInputStream(input);
7. int count = input.available();
8. byte[] ary = new byte[count];
9. inst.read(ary);
10. for (byte bt : ary) {
11. char k = (char) bt;
12. System.out.print(k+"-");
13. }
14. }
15. }
JAVA
Output:
J-A-V-A
Constructor Description
BufferedReader(Reader It is used to create a buffered character input stream
rd) uses the default size for an input buffer.
Method Description
int read(char[] cbuf, int It is used for reading characters into a portion of an arra
off, int len)
boolean It is used to test the input stream support for the mar
markSupported() reset method.
void close() It closes the input stream and releases any of the sy
resources associated with the stream.
1. package com.javatpoint;
import java.io.*;
public class BufferedReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
BufferedReader br=new BufferedReader(fr);
int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
}
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:
Class declaration
Constructor Description
Method Description
void write(char[] cbuf, int off, int It is used to write a portion of an array of
len) characters.
void write(String s, int off, int len) It is used to write a portion of a string.
Class methods
Example of Java BufferedWriter
Let's see the simple example of writing the data to a text
file testout.txt using Java BufferedWriter.
1. package com.javatpoint;
import java.io.*;
public class BufferedWriterExample {
public static void main(String[] args) throws Exception {
FileWriter writer = new FileWriter("D:\\testout.txt");
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Welcome to javaTpoint.");
buffer.close();
System.out.println("Success");
}
}
Output:
success
testout.txt:
Welcome to javaTpoint.
Java InputStreamReader
An InputStreamReader is a bridge from byte streams to character
streams: It reads bytes and decodes them into characters using a
specified charset. The charset that it uses may be specified by name or
may be given explicitly, or the platform's default charset may be
accepted.
Constructor
Method
Example
public class InputStreamReaderExample {
public static void main(String[] args) {
try {
InputStream stream = new FileInputStream("file.txt");
Reader reader = new InputStreamReader(stream);
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
I love my country
Constructor
Constructor Description
Methods
Example
1. public class OutputStreamWriterExample {
2. public static void main(String[] args) {
3.
4. try {
5. OutputStream outputStream = new FileOutputStream("output.t
xt");
6. Writer outputStreamWriter = new OutputStreamWriter(outputS
tream);
7.
8. outputStreamWriter.write("Hello World");
9.
10. outputStreamWriter.close();
11. } catch (Exception e) {
12. e.getMessage();
13. }
14. }
15. }
Output: