0% found this document useful (0 votes)
12 views17 pages

File IO

The document provides a comprehensive overview of File Input/Output (I/O) in Java, detailing key concepts such as streams, the File class, and various byte and character stream classes. It also covers advanced topics like serialization, the NIO Files class for improved file handling, and device-independent I/O programming. Examples are provided for each concept to illustrate their usage in practical scenarios.

Uploaded by

saihari292
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views17 pages

File IO

The document provides a comprehensive overview of File Input/Output (I/O) in Java, detailing key concepts such as streams, the File class, and various byte and character stream classes. It also covers advanced topics like serialization, the NIO Files class for improved file handling, and device-independent I/O programming. Examples are provided for each concept to illustrate their usage in practical scenarios.

Uploaded by

saihari292
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Detailed Notes on File I/O in Java

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. Key Concepts in File I/O

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.

o Output Stream: Writes data to a destination (e.g., a file, socket, or memory).


For example, FileOutputStream writes data byte-by-byte to 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.

2. Byte Stream Classes

1. FileInputStream:

o Reads raw bytes from a file. It is best suited for binary data.

o Example:

o import java.io.*;

o public class FileInputStreamExample {

o public static void main(String[] args) {

o try (FileInputStream fis = new FileInputStream("example.txt")) {

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 public class FileOutputStreamExample {

o public static void main(String[] args) {

o String data = "Hello, FileOutputStream!";

o try (FileOutputStream fos = new FileOutputStream("output.txt")) {

o fos.write(data.getBytes());

o } catch (IOException e) {

o e.printStackTrace();

o }

o }

o }

3. Character Stream Classes

1. FileReader:

o Reads characters from a file. Suitable for text files.

o Example:
o import java.io.*;

o public class FileReaderExample {

o public static void main(String[] args) {

o try (FileReader fr = new FileReader("example.txt")) {

o int content;

o while ((content = fr.read()) != -1) {

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 public class FileWriterExample {

o public static void main(String[] args) {

o String data = "Hello, FileWriter!";

o try (FileWriter fw = new FileWriter("output.txt")) {

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 Reads text from an input stream efficiently by buffering characters.

o Example:

o import java.io.*;

o public class BufferedReaderExample {

o public static void main(String[] args) {

o try (BufferedReader br = new BufferedReader(new


FileReader("example.txt"))) {

o String line;

o while ((line = br.readLine()) != null) {

o System.out.println(line);

o }

o } catch (IOException e) {

o e.printStackTrace();

o }

o }

o }

2. BufferedWriter:

o Writes text to an output stream efficiently by buffering characters.

o Example:

o import java.io.*;

o public class BufferedWriterExample {

o public static void main(String[] args) {

o String data = "Hello, BufferedWriter!";

o try (BufferedWriter bw = new BufferedWriter(new


FileWriter("output.txt"))) {
o bw.write(data);

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.*;

public class FileExample {

public static void main(String[] args) {

File file = new File("newfile.txt");

try {

if (file.createNewFile()) {

System.out.println("File created: " + file.getName());

} else {

System.out.println("File already exists.");

} catch (IOException e) {

e.printStackTrace();

 Common Methods:
o exists(): Checks if the file exists.

o getName(): Returns the file name.

o length(): Returns the file size in bytes.

o delete(): Deletes the file.

Example:

File file = new File("example.txt");

if (file.exists()) {

System.out.println("File name: " + file.getName());

System.out.println("File size: " + file.length() + " bytes");

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:

o A marker interface (no methods) that classes must implement to be


serialized.

2. ObjectOutputStream and ObjectInputStream:

Example:

import java.io.*;

class Person implements Serializable {

private static final long serialVersionUID = 1L;

String name;

int age;

Person(String name, int age) {

this.name = name;

this.age = age;

}
}

public class SerializationExample {

public static void main(String[] args) {

Person person = new Person("John", 30);

try (ObjectOutputStream oos = new ObjectOutputStream(new


FileOutputStream("person.ser"))) {

oos.writeObject(person);

} catch (IOException e) {

e.printStackTrace();

try (ObjectInputStream ois = new ObjectInputStream(new


FileInputStream("person.ser"))) {

Person deserializedPerson = (Person) ois.readObject();

System.out.println("Name: " + deserializedPerson.name + ", Age: " +


deserializedPerson.age);

} catch (IOException | ClassNotFoundException e) {

e.printStackTrace();

7.

File Operations with NIO

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.

Key Features of the Files Class


 Simplifies file and directory manipulation.

 Offers better error handling with exceptions.

 Provides utilities for handling file attributes.

 Works with Path objects introduced in java.nio.file.

Common Methods of the Files Class with Examples

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;

public class FileReadExample {

public static void main(String[] args) {

Path filePath = Paths.get("example.txt");

try {

// Read file as a byte array

byte[] fileBytes = Files.readAllBytes(filePath);

System.out.println(new String(fileBytes));

// Read file as a list of lines

Files.readAllLines(filePath).forEach(System.out::println);

} catch (IOException e) {

System.err.println("Error reading file: " + e.getMessage());

}
}

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;

public class FileWriteExample {

public static void main(String[] args) {

Path filePath = Paths.get("output.txt");

String content = "This is some sample text.";

try {

// Write text to the file (overwrites if file exists)

Files.write(filePath, content.getBytes());

// Append a list of strings to the file

List<String> lines = List.of("Line 1", "Line 2", "Line 3");

Files.write(filePath, lines, StandardOpenOption.APPEND);

System.out.println("File written successfully.");

} catch (IOException e) {

System.err.println("Error writing file: " + e.getMessage());

}
}

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;

public class FileCopyExample {

public static void main(String[] args) {

Path sourcePath = Paths.get("source.txt");

Path targetPath = Paths.get("target.txt");

try {

Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);

System.out.println("File copied successfully.");

} catch (IOException e) {

System.err.println("Error copying file: " + e.getMessage());

4. Moving a File

The Files.move() method moves or renames a file or directory.

Example:

import java.nio.file.*;

import java.io.IOException;
public class FileMoveExample {

public static void main(String[] args) {

Path sourcePath = Paths.get("source.txt");

Path targetPath = Paths.get("moved.txt");

try {

Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);

System.out.println("File moved successfully.");

} catch (IOException e) {

System.err.println("Error moving file: " + e.getMessage());

5. Deleting a File

The Files.delete() method deletes a file or directory.

Example:

import java.nio.file.*;

import java.io.IOException;

public class FileDeleteExample {

public static void main(String[] args) {

Path filePath = Paths.get("example.txt");

try {

Files.delete(filePath);

System.out.println("File deleted successfully.");

} catch (IOException e) {
System.err.println("Error deleting file: " + e.getMessage());

6. Checking File Existence

The Files.exists() method checks whether a file or directory exists.

Example:

import java.nio.file.*;

public class FileExistsExample {

public static void main(String[] args) {

Path filePath = Paths.get("example.txt");

if (Files.exists(filePath)) {

System.out.println("File exists.");

} else {

System.out.println("File does not exist.");

7. Creating a Directory

The Files.createDirectory() method creates a new directory.

Example:

import java.nio.file.*;

import java.io.IOException;
public class CreateDirectoryExample {

public static void main(String[] args) {

Path dirPath = Paths.get("newDirectory");

try {

Files.createDirectory(dirPath);

System.out.println("Directory created successfully.");

} catch (IOException e) {

System.err.println("Error creating directory: " + e.getMessage());

Notes on Error Handling

 FileNotFoundException: Common when trying to access a non-existent file.

 IOException: General exception for I/O errors.

 SecurityException: Thrown if file access is denied.

Advantages of Using Files Class

 Supports large files and efficient operations.

 Provides methods to handle symbolic links.

 Simplifies file attribute handling with classes like BasicFileAttributes.

By leveraging the Files class and its methods, Java developers can efficiently handle file
operations while writing clean and maintainable code.

1. The "transient" Properties of a Class:


In Java, the transient keyword is used to indicate that a particular field of a class should not
be serialized when the object of the class is converted into a byte stream (e.g., for saving to
a file or sending over a network). Serialization is the process of converting an object's state
into a format that can be stored or transmitted, and deserialization is the reverse.

Key Points About transient:

 Fields marked as transient are skipped during serialization.

 Useful for sensitive information (like passwords) or for fields that are not serializable
(e.g., open file streams, sockets).

Example:

import java.io.*;

class User implements Serializable {

private static final long serialVersionUID = 1L;

String name;

transient String password; // This field won't be serialized

public User(String name, String password) {

this.name = name;

this.password = password;

public class TransientExample {

public static void main(String[] args) {

User user = new User("JohnDoe", "secretPassword");

// Serialize the object

try (ObjectOutputStream oos = new ObjectOutputStream(new


FileOutputStream("user.ser"))) {

oos.writeObject(user);
} catch (IOException e) {

e.printStackTrace();

// Deserialize the object

try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user.ser")))


{

User deserializedUser = (User) ois.readObject();

System.out.println("Name: " + deserializedUser.name); // Output: JohnDoe

System.out.println("Password: " + deserializedUser.password); // Output: null (not


serialized)

} catch (IOException | ClassNotFoundException e) {

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.

2. Writing Device-Independent Input/Output Programs:

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:

 Streams Abstraction: Java provides InputStream and OutputStream for byte-based


I/O and Reader and Writer for character-based I/O.
 File Handling: Programs can handle files, but the same logic can often be applied to
sockets or in-memory streams without modification.

 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.*;

public class DeviceIndependentIO {

public static void main(String[] args) {

// Device-independent file reading

try (Reader reader = new FileReader("example.txt");

Writer writer = new FileWriter("output.txt")) {

int data;

while ((data = reader.read()) != -1) { // Reading character by character

writer.write(data); // Writing to output file

System.out.println("Data successfully copied to output.txt!");

} catch (IOException e) {

e.printStackTrace();

Explanation:

1. Reader and Writer:

o FileReader reads data from a file as characters.


o FileWriter writes data to a file as characters.

2. Flexibility:

o You could replace FileReader with InputStreamReader (to read from


keyboard) or BufferedReader (to read efficiently), making the program device-
independent.

Advantages of Device-Independent I/O:

 Code reusability across different I/O sources or destinations.

 Simplified development using Java's I/O abstractions.

 Cleaner and more maintainable code.

Let me know if you'd like deeper explanations of either topic!

You might also like