File Handling in Java
File Handling in Java
File handling in Java is an essential topic for dealing with reading and writing files.
1. **File Class**:
- The `File` class in java.io package provides methods to create, delete, and check properties of
files.
- Example:
```java
if (myFile.exists()) {
System.out.println("File exists");
} else {
```
- Example:
```java
writer.write("Hello, World!");
writer.close();
FileReader reader = new FileReader("output.txt");
int character;
System.out.print((char) character);
reader.close();
```
- Example:
```java
writer.close();
String line;
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
int byteData;
outputStream.write(byteData);
inputStream.close();
outputStream.close();
```
5. **Try-with-Resources**:
- Example:
```java
} catch (IOException e) {
e.printStackTrace();
```