Reading and writing files is a common task in Java programming. In this explanation, we’ll cover how to read and write files in Java using the java.io package.
Reading Files
To read a file in Java, you can use the FileReader class. Here’s an example:
try {
FileReader reader = new FileReader("file.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
} catch (IOException e) {
e.printStackTrace();
}
In this example, we have created a new FileReader object for the file named “file.txt”. We then read the file character by character using the read method and printed each character to the console.
Writing Files
To write to a file in Java, you can use the FileWriter class. Here’s an example:
try {
FileWriter writer = new FileWriter("file.txt");
writer.write("Hello, World!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
In this example, we have created a new FileWriter object for the file named “file.txt”. We then used the write method to write the string “Hello, World!” to the file. Finally, we closed the FileWriter object to free up system resources.
Reading and Writing Binary Files
To read and write binary files in Java, you can use the FileInputStream and FileOutputStream classes. Here’s an example of reading a binary file:
try {
FileInputStream stream = new FileInputStream("file.bin");
byte[] buffer = new byte[1024];
while (stream.read(buffer) != -1) {
// process the buffer
}
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
In this example, we have created a new FileInputStream object for the file named “file.bin”. We then read the file using a byte buffer and processed each buffer as it was read.
Here’s an example of writing a binary file:
try {
FileOutputStream stream = new FileOutputStream("file.bin");
byte[] data = new byte[] { 0x01, 0x02, 0x03 };
stream.write(data);
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
In this example, we have created a new FileOutputStream object for the file named “file.bin”. We then wrote the byte array { 0x01, 0x02, 0x03 } to the file.
These are just a few examples of how to read and write files in Java. The java.io package provides many more classes and methods for handling files, so be sure to check out the Java documentation for more information.