Reading and writing data from/to files is a common task in programming. In Java, you can read and write data from/to files using the java.io
package. In this article, we will explore how to read and write data from/to files in Java with examples.
Reading data from files
To read data from a file, you can use the FileReader
and BufferedReader
classes. The FileReader
class is used to read character files, while the BufferedReader
class provides buffering and efficient reading of character streams.
Here’s an example that shows how to read data from a file:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, we use the BufferedReader
class to read data from a file called data.txt
. We open the file using the FileReader
class, which takes the name of the file as a parameter. We then use the readLine
method to read each line of the file, and we print the lines to the console.
Writing data to files
To write data to a file, you can use the FileWriter
and BufferedWriter
classes. The FileWriter
class is used to write character files, while the BufferedWriter
class provides buffering and efficient writing of character streams.
Here’s an example that shows how to write data to a file:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileExample {
public static void main(String[] args) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
writer.write("Hello, world!");
writer.newLine();
writer.write("This is a test file.");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, we use the BufferedWriter
class to write data to a file called output.txt
. We open the file using the FileWriter
class, which takes the name of the file as a parameter. We then use the write
method to write the data to the file, and we use the newLine
method to add a new line to the file. Finally, we close the writer using the close
method.
Conclusion
In this article, we’ve learned how to read and write data from/to files in Java using the java.io
package. By using the FileReader
, BufferedReader
, FileWriter
, and BufferedWriter
classes, you can easily read and write data from/to files in your Java programs.