# File handling

### Introduction to File Handling

File handling is a crucial aspect of programming as it allows data to be saved and accessed in files. It enables a program to store data permanently, which can then be used by the program in future executions.

### Reading and Writing Files:

In Java, we can use the `File` class to represent a file and the `FileWriter` and `FileReader` classes to read and write files. The following code snippet demonstrates how to write data to a file using `FileWriter`:

```java
import java.io.FileWriter;
import java.io.IOException;

public class FileWriterDemo {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("output.txt");
            writer.write("Hello, World!");
            writer.close();
            System.out.println("Data written to file.");
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}
```

### Working with Text Files and Binary Files:

Java provides different classes to handle text files and binary files. The `FileWriter` and `FileReader` classes are used to read and write text files, while the `ObjectOutputStream` and `ObjectInputStream` classes are used to read and write binary files. The following code snippet demonstrates how to write an object to a binary file using `ObjectOutputStream`:

```java
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;

public class ObjectOutputStreamDemo {
    public static void main(String[] args) {
        try {
            FileOutputStream fos = new FileOutputStream("data.dat");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            Person person = new Person("John", 25);
            oos.writeObject(person);
            oos.close();
            fos.close();
            System.out.println("Object written to file.");
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}
```

### Error Handling:

When working with files, it is important to handle errors that may occur. This can be achieved using try-catch blocks. The following code snippet demonstrates how to read data from a file using `FileReader` and handle any errors that may occur:

```java
import java.io.FileReader;
import java.io.IOException;

public class FileReaderDemo {
    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("input.txt");
            int data = reader.read();
            while (data != -1) {
                System.out.print((char) data);
                data = reader.read();
            }
            reader.close();
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}
```

In the above code snippet, we are reading data from a file using `FileReader` and displaying it to the console. The `read()` method of `FileReader` returns -1 if the end of the file is reached.

Overall, file handling is an important aspect of programming and is useful in a variety of applications, from storing user preferences to saving game progress.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://pankhaniyajay.gitbook.io/introduction-to-programming-fundamentals-java/file-handling.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
