Java I-O
Java I-O
} catch (IOException e) {
e.printStackTrace();
} finally {
FileOutputStream Class
• Java FileOutputStream is an output stream used for writing data to a
file.
• 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.
Java Program: Writing Data to a File using FileOutputStream
import java.io.FileOutputStream;
import java.io.IOException; catch (IOException e) {
e.printStackTrace();
public class FileOutputStreamExample{ }
}
BufferedInputStream Class
• Java BufferedInputStream class is used to read information from
stream.
Constructor:
Constructor Description
It creates the BufferedInputStream and saves it
BufferedInputStream(InputStream IS)
argument, the input stream IS, for later use.
Method:
int read() :It read the next byte of data from the input stream.
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
Methods:
Method Description
void write(int b) It writes the specified byte to the buffered output stream.
void flush() It flushes the buffered output stream.
import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D://javaprogs/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");
}
}
ObjectOutputStream:
The purpose of ObjectOutputStream in Java is to serialize objects,
which means converting an object’s state intoa sequence of bytes.
These bytes can then be saved to a file, transmitted over a network,
or stored in a database.
ate an ObjectOutputStream
reates a FileOutputStream where objects from ObjectOutputStream are written
eOutputStream fileStream = new FileOutputStream(String file);
thods
te() - writes a byte of data to the output stream
teBoolean() - writes data in boolean form
teChar() - writes data in character form
teInt() - writes data in integer form
teObject() - writes object to the output stream
ObjectInputStream Class
The ObjectInputStream class of the java.io package can be used to read objects that were
previously written by ObjectOutputStream.
Working of ObjectInputStream
• The ObjectInputStream is mainly used to read data written by the ObjectOutputStream.
• Basically, the ObjectOutputStream converts Java objects into corresponding streams. This is known
as serialization. Those converted streams can be stored in files or transferred through networks.
• Now, if we need to read those objects, we will use the ObjectInputStream that will convert the
streams back to corresponding objects. This is known as deserialization.
Methods
Create an ObjectInputStream • readBoolean() - reads data in boolean form
•readChar() - reads data in character form
// Creates a file input stream linked with the specified file •readInt() - reads data in integer form
•readObject() - reads the object from the
FileInputStream fileStream = new FileInputStream(String file);
input stream
// Creates an object input stream using the file input stream •read() - reads a byte of data from the input
stream
ObjectInputStream objStream = new ObjectInputStream(fileStream);
import java.io.FileInputStream; // Reads data using the ObjectInputStream
import java.io.FileOutputStream; FileInputStream fileStream = new
import java.io.ObjectInputStream; FileInputStream("file.txt");
import java.io.ObjectOutputStream; ObjectInputStream objStream = new
ObjectInputStream(fileStream);
class FileOutputStreamEX1{
public static void main(String[] args) { System.out.println("Integer data :" +
objStream.readInt());
int data1 = 5; System.out.println("String data: " +
String data2 = "This is programiz"; objStream.readObject());
try { output.close();
objStream.close();
FileOutputStream file = new FileOutputStream("file.txt"); }
1. BufferedReader This class provides methods to read characters from the buffer.
2. CharArrayReader This class provides methods to read characters from the char array.
3. FileReader This class provides methods to read characters from the file.
SN Method Description
This method returns the integral representation of the next character
1 int read() present in the input. It returns -1 if the end of the input is
encountered.
Writer Class child classes
SN Class Description
6 StringWriter This class provides methods to write the characters to the string.
Write Class Methods:
SN Method Description
This method is used to write the data to the output
1 void write()
stream.
This method is used to write a single character to
2 void write(int i)
the output stream.
This method is used to write the array of characters
3 Void write(char buffer[]) to the output stream.
Methods
It is used to return a character in ASCII form. It returns -1 at the end
int read() of file.
//In this example, we are reading the data from the text file testout.txt using
Java FileReader class.
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. }
FileWriter Class
• Java FileWriter class is used to write character-oriented data to a file.
• Unlike FileOutputStream class, you don't need to convert string into
byte array because it provides method to write string directly.
Constructors
Constructor Description
FileWriter(String file) Creates a new file. It gets file name in string.
Methods
Method Description
void write(String text) It is used to write the string into FileWriter.
void write(char c) It is used to write the char into FileWriter.
void write(char[] c) It is used to write char array into FileWriter.
void flush() It is used to flushes the data of FileWriter.
void close() It is used to close the FileWriter.
FileWriter Example
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. }
BufferedReader Class
• Java BufferedReader class is used to read the text from a character-
based input stream.
• It can be used to read data line by line using readLine() method. It
makes the performance fast.
• It inherits Reader class.
constructors
Constructor Description
It is used to create a buffered character input stream that uses the
BufferedReader(Reader rd)
default size for an input buffer.
Methods
Method Description
int read() It is used for reading a single character.
int read(char[] cbuf, int off, int len) It is used for reading characters into a portion of an array.
String readLine() It is used for reading a line of text.
It closes the input stream and releases any of the system
void close()
resources associated with the stream.
BufferedReader Example
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. }
Using FileReader and FileWriter, write a program to perform file
copying and any other suitable operations.
import java.io.FileReader; // Read each character and write it to the destination file
import java.io.FileWriter; while ((data = reader.read()) != -1) {
writer.write(data);
import java.io.IOException;
characterCount++;
}
public class FileCopy {
public static void main(String[] args) { System.out.println("File copied successfully!");
System.out.println("Total characters copied: " +
FileReader reader = null;
characterCount);
FileWriter writer = null; } catch (IOException e) {
int characterCount = 0; System.out.println("An error occurred: " +
e.getMessage());
} finally {
try {
try {
// Specify the source and destination files // Close FileReader and FileWriter to free resources
String sourceFile = "source.txt"; if (reader != null) reader.close();
String destFile = "destination.txt"; if (writer != null) writer.close();
} catch (IOException e) {
System.out.println("Failed to close resources: " +
// Create FileReader and FileWriter objects e.getMessage());
reader = new FileReader(sourceFile); }
writer = new FileWriter(destFile); }
}
}
int data;
Write a Java Program that displays the number of characters, lines and
words in a text file.
import java.io.BufferedReader; charCount += line.length(); // Add number of
import java.io.FileReader; characters in the current line
import java.io.IOException;
// Split the line into words and count them
public class FileStatistics { String[] words = line.split(“ "); // Regex for spaces,
tabs, etc.
public static void main(String[] args) {
wordCount += words.length;
// Path to the file
}
String filePath = "sample.txt"; // Update this with the
actual file path
// Output the results
int charCount = 0; System.out.println("Number of characters: " +
charCount);
int wordCount = 0;
System.out.println("Number of words: " +
int lineCount = 0; wordCount);
System.out.println("Number of lines: " + lineCount);
try (BufferedReader reader = new
BufferedReader(new FileReader(filePath))) { } catch (IOException e) {
String line; System.out.println("An error occurred while reading
the file: " + e.getMessage());
// Read the file line by line }
while ((line = reader.readLine()) != null) { }
lineCount++; // Increment line count }
Predefined Streams:
In java “System” is a class which contains three predefined stream
variables:
1. In
2. Out
3. err.
These fields are declared as public, static, and final within System.
• System.out refers to the standard output stream(console o/p:
monitor).
• System.in refers to standard input (console i/p: keyboard)
• System.err refers to the standard error stream(which also is the
console by default).
Reading Console Input:
In java, console input read by following statement.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
Here,
• BufferedReader character stream class which connect to the System.in through
InputStreamReader .
• InputStreamReader can converts bytes to characters.
Java program that uses BufferedReader to read different types of values
It provides a formatted prompt then reads the single line of text from
String readLine(String fmt, Object... args)
the console.
char[] readPassword() It is used to read password that is not being displayed on the console.
char[] readPassword(String fmt, Object... It provides a formatted prompt then reads the password that is not
args) being displayed on the console.
Console format(String fmt, Object... args) It is used to write a formatted string to the console output stream.
import java.util.Scanner;
sc.close();
}
}
import java.io.File; // Example: Reading line by line
import java.io.FileNotFoundException; while (sc.hasNextLine()) {
import java.util.Scanner; String line = sc.nextLine();
System.out.println("Line: " + line);
public class ScannerFromFileExample { }
public static void main(String[] args) {
try { // Step 4: Close the scanner
// Step 1: Create a File object for the file sc.close();
you want to read
File file = new File("example.txt"); } catch (FileNotFoundException e) {
System.out.println("File not found. Please
// Step 2: Create a Scanner object that check the file path.");
reads from the file e.printStackTrace();
Scanner sc = new Scanner(file); }
}
// Step 3: Use the Scanner to read the }
contents of the file
File Class
• The File class is an abstract representation of file and directory
pathname. A pathname can be either absolute or relative.
• The File class have several methods for working with directories and
files such as creating new directories or files, deleting and renaming
directories or files, listing the contents of a directory etc.
Constructors
Constructor Description
It creates a new File instance from a
File(File parent, String child) parent abstract pathname and a
child pathname string.
It creates a new File instance by
File(String pathname) converting the given pathname
string into an abstract pathname.
It creates a new File instance from a
File(String parent, String child) parent pathname string and a child
pathname string.
It creates a new File instance by
File(URI uri) converting the given file: URI into an
abstract pathname.
1. File(File parent, String child)
This constructor creates a new File instance from a parent directory (as a File
object) and a child file name (as a String).
import java.io.File;
public class FileConstructorExample1{
public static void main(String[] args) {
// Parent directory as a File object
File parentDir = new File("D:\\javaprogs");
// Creating the File object using the parent directory and child file name
File file = new File(parentDir, childFile);
import java.io.File;
// Creating the File object using the parent directory and child file name
File file = new File(parentDir, childFile);