File Handling in Java
File handling in Java is an essential topic for dealing with reading and writing files.
Here's a quick rundown of the basics:
1. **File Class**:
- The `File` class in java.io package provides methods to create, delete, and check properties of
files.
- Example:
```java
File myFile = new File("filename.txt");
if (myFile.exists()) {
System.out.println("File exists");
} else {
System.out.println("File does not exist");
```
2. **FileReader and FileWriter**:
- `FileReader` is used to read the contents of a file character by character.
- `FileWriter` is used to write characters to a file.
- Example:
```java
FileWriter writer = new FileWriter("output.txt");
writer.write("Hello, World!");
writer.close();
FileReader reader = new FileReader("output.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
reader.close();
```
3. **BufferedReader and BufferedWriter**:
- `BufferedReader` reads text from an input stream efficiently by buffering characters.
- `BufferedWriter` writes text to an output stream, buffering characters to enhance performance.
- Example:
```java
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
writer.write("Buffered writing is fast!");
writer.close();
BufferedReader reader = new BufferedReader(new FileReader("output.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
reader.close();
```
4. **FileInputStream and FileOutputStream**:
- These are used for reading and writing binary data (like images or videos).
- Example:
```java
FileInputStream inputStream = new FileInputStream("input.jpg");
FileOutputStream outputStream = new FileOutputStream("output.jpg");
int byteData;
while ((byteData = inputStream.read()) != -1) {
outputStream.write(byteData);
inputStream.close();
outputStream.close();
```
5. **Try-with-Resources**:
- Automatically closes file resources to prevent memory leaks.
- Example:
```java
try (FileWriter writer = new FileWriter("output.txt")) {
writer.write("Automatic resource management!");
} catch (IOException e) {
e.printStackTrace();
```