File IO
File IO
File Input/Output (I/O) in Java is a mechanism that allows programs to read data from and
write data to files. Java provides several classes in the java.io and java.nio packages to
handle file operations efficiently.
1. Streams:
Streams in Java represent a sequence of data. They abstract the complexity of data handling
and provide a clean interface for reading and writing data. Streams can be categorized into:
o Input Stream: Reads data from a source (e.g., a file, socket, or memory). For
example, FileInputStream reads data byte-by-byte from a file.
2. Types of Streams:
o Byte Streams: Handles raw binary data such as images or audio files. Classes
include InputStream and OutputStream.
o Character Streams: Handles text data (characters) and is suitable for handling
files with textual content. Classes include Reader and Writer.
3. File Class:
The File class in Java represents file and directory pathnames. It provides methods for
creating, deleting, and checking file properties, offering an abstraction over file systems.
1. FileInputStream:
o Reads raw bytes from a file. It is best suited for binary data.
o Example:
o import java.io.*;
o int content;
o while ((content = fis.read()) != -1) {
o System.out.print((char) content);
o }
o } catch (IOException e) {
o e.printStackTrace();
o }
o }
o }
2. FileOutputStream:
o Writes raw bytes to a file. Useful for writing binary data, such as image or
audio files.
o Example:
o import java.io.*;
o fos.write(data.getBytes());
o } catch (IOException e) {
o e.printStackTrace();
o }
o }
o }
1. FileReader:
o Example:
o import java.io.*;
o int content;
o System.out.print((char) content);
o }
o } catch (IOException e) {
o e.printStackTrace();
o }
o }
o }
2. FileWriter:
o Writes characters to a file. Ideal for creating and modifying text files.
o Example:
o import java.io.*;
o fw.write(data);
o } catch (IOException e) {
o e.printStackTrace();
o }
o }
o }
4. Buffered Streams
Buffered streams improve performance by reducing the number of I/O operations. They
achieve this by storing data temporarily in memory (buffer) before reading or writing.
1. BufferedReader:
o Example:
o import java.io.*;
o String line;
o System.out.println(line);
o }
o } catch (IOException e) {
o e.printStackTrace();
o }
o }
o }
2. BufferedWriter:
o Example:
o import java.io.*;
o } catch (IOException e) {
o e.printStackTrace();
o }
o }
o }
5. File Class
The File class is part of the java.io package and provides various methods for file and
directory management.
Creating a File:
Example:
import java.io.*;
try {
if (file.createNewFile()) {
} else {
} catch (IOException e) {
e.printStackTrace();
Common Methods:
o exists(): Checks if the file exists.
Example:
if (file.exists()) {
6. Serialization
Serialization is the process of converting an object into a byte stream so it can be saved to a
file or transmitted over a network. Deserialization is the reverse process.
1. Serializable Interface:
Example:
import java.io.*;
String name;
int age;
this.name = name;
this.age = age;
}
}
oos.writeObject(person);
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
7.
Java introduced the Files class in Java 7 as part of the java.nio.file package. It provides a rich
set of methods for performing file operations such as reading, writing, copying, moving,
deleting files, and many more. This class simplifies file handling and improves performance
compared to earlier file handling mechanisms in Java.
1. Reading a File
The Files.readAllBytes() and Files.readAllLines() methods can be used to read the content of
a file.
Example:
import java.nio.file.*;
import java.io.IOException;
try {
System.out.println(new String(fileBytes));
Files.readAllLines(filePath).forEach(System.out::println);
} catch (IOException e) {
}
}
2. Writing to a File
The Files.write() method can be used to write data to a file. This method allows overwriting
or appending content.
Example:
import java.nio.file.*;
import java.io.IOException;
import java.util.List;
try {
Files.write(filePath, content.getBytes());
} catch (IOException e) {
}
}
3. Copying a File
The Files.copy() method allows copying a file or directory from one location to another.
Example:
import java.nio.file.*;
import java.io.IOException;
try {
} catch (IOException e) {
4. Moving a File
Example:
import java.nio.file.*;
import java.io.IOException;
public class FileMoveExample {
try {
} catch (IOException e) {
5. Deleting a File
Example:
import java.nio.file.*;
import java.io.IOException;
try {
Files.delete(filePath);
} catch (IOException e) {
System.err.println("Error deleting file: " + e.getMessage());
Example:
import java.nio.file.*;
if (Files.exists(filePath)) {
System.out.println("File exists.");
} else {
7. Creating a Directory
Example:
import java.nio.file.*;
import java.io.IOException;
public class CreateDirectoryExample {
try {
Files.createDirectory(dirPath);
} catch (IOException e) {
By leveraging the Files class and its methods, Java developers can efficiently handle file
operations while writing clean and maintainable code.
Useful for sensitive information (like passwords) or for fields that are not serializable
(e.g., open file streams, sockets).
Example:
import java.io.*;
String name;
this.name = name;
this.password = password;
oos.writeObject(user);
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
Output:
Name: JohnDoe
Password: null
In this example, the password field is marked transient, so it is not serialized and appears as
null when the object is deserialized.
Device-independent input/output programming means writing code that can handle data
regardless of the source (e.g., file, network, keyboard) or destination (e.g., file, console,
network). Java's java.io and java.nio packages provide abstractions for this purpose, allowing
you to write programs that work seamlessly across various I/O devices.
Key Features:
Buffered I/O: Classes like BufferedReader and BufferedWriter optimize reading and
writing, ensuring device-independence and efficiency.
Example:
Here's an example that reads data from a file but can easily be modified to read from other
sources, such as a network socket:
import java.io.*;
int data;
} catch (IOException e) {
e.printStackTrace();
Explanation:
2. Flexibility: