File Handling in Java: Reading and Writing Files


Introduction to File Handling

File handling in Java involves the process of creating, reading, and writing to files. It's a fundamental task in software development, allowing you to store and retrieve data in a persistent manner. In this guide, we'll explore how to work with files using Java.


Reading from a File

To read from a file in Java, you typically use the FileInputStream and BufferedReader classes. Here's an example of reading text from a file:


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("sample.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Writing to a File

To write to a file, you can use the FileOutputStream and BufferedWriter classes. Here's an example of writing text to a file:


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFile {
public static void main(String[] args) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
writer.write("Hello, File Handling in Java!");
} catch (IOException e) {
e.printStackTrace();
}
}
}

Working with Files

Java provides various classes and methods for working with files, including checking if a file exists, creating directories, deleting files, and more. Here's an example of checking if a file exists:


import java.io.File;
public class FileExists {
public static void main(String[] args) {
File file = new File("sample.txt");
if (file.exists()) {
System.out.println("File exists!");
} else {
System.out.println("File does not exist.");
}
}
}

Conclusion

File handling is a critical aspect of Java programming, allowing you to interact with files and store data persistently. You've learned how to read from and write to files, check for file existence, and handle file-related exceptions in this guide. As you continue to develop Java applications, mastering file handling will be essential for working with data and files.