Reading text files using FileReader
The simplest way to load a text file in Java is by using the FileReader class. The FileReader class enables you to read data from a file and store it in a character array buffer. Here is a simple example that demonstrates how to use the FileReader class:// Create an instance of FileReader and specify the path of the text fileFileReader fileReader = new FileReader(\"path/to/file.txt\");// Create a character array to store the datachar[] buffer = new char[1024];// Use the read() method to read the data from the fileint numCharsRead = fileReader.read(buffer);// Convert the character array to a StringString data = new String(buffer, 0, numCharsRead);// Close the FileReaderfileReader.close();
Reading text files using BufferedReader
The BufferedReader class is another option for loading a text file in Java. It is similar to the FileReader class, but it provides additional features to simplify reading text files. Here is a basic example that demonstrates how to use the BufferedReader class:// Create an instance of BufferedReader and specify the path of the text fileBufferedReader bufferedReader = new BufferedReader(new FileReader(\"path/to/file.txt\"));// Use the readLine() method to read each line from the fileString line;while ((line = bufferedReader.readLine()) != null) { // Print each line to the console System.out.println(line);}// Close the BufferedReaderbufferedReader.close();
Handling Exceptions
When working with files in Java, it is important to handle exceptions properly. If you attempt to read a file that does not exist or is not accessible, an exception will be thrown. To prevent your program from crashing, you should handle these exceptions using a try-catch block. Here is an example of how to handle exceptions when loading a text file:try { // Create an instance of FileReader and specify the path of the text file FileReader fileReader = new FileReader(\"path/to/file.txt\"); // Create a character array to store the data char[] buffer = new char[1024]; // Use the read() method to read the data from the file int numCharsRead = fileReader.read(buffer); // Convert the character array to a String String data = new String(buffer, 0, numCharsRead); // Close the FileReader fileReader.close();} catch (IOException e) { // Handle the exception by printing the error message to the console e.printStackTrace();}