If you have any query feel free to chat us!
Happy Coding! Happy Learning!
File handling in Java refers to the process of reading data from files or writing data to files. Java provides several classes and methods in its standard library to perform file handling operations, making it easy to work with files in a platform-independent manner.
Key classes for file handling in Java include:
File
class represents a file or directory path on the file system.FileInputStream
class is used to read data from a file, while FileOutputStream
is used to write data to a file.BufferedReader
and BufferedWriter
classes are used for character-level file handling.FileReader
and FileWriter
classes are used to read and write text files.FileInputStream
and FileOutputStream
, and they work with characters instead of bytes.Here's a simple example of reading and writing data to a file in Java:
javaCopy code
import java.io.*;
public class FileHandlingExample {
public static void main(String[] args) {
// Writing data to a file
try (FileWriter writer = new FileWriter("data.txt")) {
writer.write("Hello, this is a sample text.\n");
writer.write("Writing data to a file in Java.");
} catch (IOException e) {
e.printStackTrace();
}
// Reading data from a file
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, the program writes two lines of text to a file named "data.txt" using FileWriter
. Then, it reads the content of the file line by line using BufferedReader
and displays it on the console.
When working with file handling operations in Java, it's essential to handle exceptions properly, close the file resources after usage (using try-with-resources), and ensure platform independence by using appropriate methods from the File
class.
Comments: 0