File Handling IO Basics
File Handling IO Basics
• Two of the most important are read( ) and write( ), which read and
write bytes of data.
FileInputStream
• FileInputStream in Java is a class that allows you to read bytes from a file. It's part
of the I/O (Input/Output) classes provided by Java to handle file operations.
• We can create an instance of this class by supplying a File or a path name, using
these two constructors:
1. FileInputStream(File file)
Example:
File f = new File(“Sample.txt”);
FileInputStream fin = new FileInputStream(f);
2.FileInputStream(String name)
FileInputStream fin = new FileInputStream(“sample.txt”);
Methods implemented by FileInputStream class
Methods Description
int available() returns an estimate of the number of remaining bytes that can be read.
int read() reads one byte of data, returns the byte as an integer value.
Return -1 if the end of the file is reached
int read(byte[]) reads a chunk of bytes to the specified byte array, up to the size of the
array. This method returns -1 if there’s no more data or the end of the file
is reached.
int read(byte[], int offset, reads up to length bytes of data from the input stream.
int length)
long skip(long n) skips over and discards n bytes of data from the input stream. This method
returns the actual number of bytes skipped.
void close() Closes this file input stream and releases any system resources associated
with the stream.
• Almost all methods throw IOException so remember to handle or
declare to throw it in your code.
Write a program to read and display
the file contents using ByteStream
class
import java.io.*;
public class ReadFile {
public static void main(String args[]) {
try{
FileInputStream in = new FileInputStream(“example.txt”);
int c;
while((c=in.read())!=-1){
System.out.println((char)c);
}
}
catch(FileNotFoundException e){
System.out.println(e.getMessage());
}
catch(IOException e){
System.out.println(e.getMessage());
}
} // end of main
} // end of class
Explanation
• Creates a FileInputStream object named in to read the file "example.txt".
FileInputStream in = new FileInputStream("example.txt");
• Reads the file content byte by byte using in.read() method until the end of the file (-1)
is reached.
• For each byte read, it converts the integer value to a character and prints it to the
console.
System.out.println((char)c);
• If the file "example.txt" is not found, it catches a FileNotFoundException and prints its
error message.
• If there is any error in reading a file, it catches a IOException and prints its error
message.
FileOutputStream
2. FileOutputStream(String name, boolean append): if append is true, then the bytes will be written to the
end of an existing file rather than the beginning.
Example:
FileOutputStream f = new FileOutputStream("output.txt", true);
3. FileOutputStream(File file)
Example:
File f = new File("output.txt");
FileOutputStream fout = new FileOutputStream(f);
void close() Closes this file output stream and releases any system resources
associated with the stream.
Write a program to get the string
from the user and write in a file
using ByteStream class
import java.util.*;
import java.io.*;
public class FileOutputStreamExample {
public static void main(String[] args) {
String s;
Scanner sc=new Scanner(System.in);
System.out.println("Enter data to be written in file");
s = sc.nextLine();
try {
FileOutputStream f= new FileOutputStream("output.txt");
byte[] arr = s.getBytes();
f.write(arr);
f.close();
System.out.println("Data has been written to the file.");
}
catch (IOException e) {
e.printStackTrace();
}
} //end of main
} // end of class
Write a program to copy from one file to another using Byte
Stream classes – FileInputStream & FileOutputStream.
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
Count the number of characters,
words and lines in a file
import java.io.*;
class FileDemo{
public static void main(String[] args){
try{
FileInputStream in = new FileInputStream("sample.txt");
int c = in.read();
int charcount =0;
int linecount =0;
int wordcount =0;
while(c!=-1){
charcount++;
c = in.read();
if(c==32 || c==10){
wordcount++;
}
if(c==10){
linecount++;
}
}
System.out.println("char count "+charcount);
System.out.println("Word count "+(wordcount+1));
System.out.println("Line count "+(linecount+1));
in.close();
}
catch(IOException e){
}
}
}
Reading and writing
Files
(Character Stream)
Character Stream
• Character streams are defined by using two class hierarchies
• Reader and Writer
• The character stream classes are in java.io package
FileReader
• FileReader is another class in Java used for reading characters from a
file rather than bytes
• It's a subclass of InputStreamReader that reads data in the form of
characters from a file in a file system.
Constructor of FileReader class:
1. FileReader(File file): This constructor takes a File object representing
the file to be read and creates a FileReader object associated with that
file.
Example:
File file = new File("example.txt");
FileReader fileReader = new FileReader(file);
Methods Description
int read() reads a single character and returns the
character as an integer value.
int read(char[] cbuf) reads characters to an array and returns the number of characters
read.
int read(char[] cbuf, int offset, reads characters to a portion of an array and returns the number
int length) of characters read.
int read(CharBuffer target) reads characters into a character buffer and returns the number of
characters added to the buffer.
Write a program to read and display
the file contents using
CharacterStream class
import java.io.*;
public class ReadFile {
public static void main(String[] args) {
try {
FileReader f = new FileReader("example.txt");
int c;
while ((c = f.read()) != -1) {
System.out.print((char) c);
}
f.close();
}
catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
catch (IOException e) {
System.out.println("Error reading the file: " + e.getMessage());
}
}
}
FileWriter
• FileWriter is used for writing characters to a file. It's a subclass of
OutputStreamWriter that writes character-based data to a file in the file system.
Constructors:
1. FileWriter(String fileName): This constructor creates a FileWriter object associated
with the file specified by the given file name.
Example:
FileWriter f = new FileWriter("output.txt");
• Reads text from a character-input stream, buffering characters to provide for the efficient reading of characters, arrays,
and lines.
• The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.
• In general, each read request made of a Reader causes a corresponding read request to be made of the underlying
character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read()
operations may be costly, such as FileReaders and InputStreamReaders. For example,