so I was tasked with writing and reading TextFiles in java, and I managed to successfully write a TextFile and display the contents (First Names) in the new file called "FirstNames". I am supposed to use the try-catch block to accomplish this task, however, I am unable to successfully read the file back, as it produces some errors that I am unable to fix. Any help would be greatly appreciated!
My Code:
// Import file
Import java.io.*;
// Import file reader
import java.io.FileReader;
// Import IOException to handle any errors
import java.io.IOException;
// Create class and method
class Main {
public static void main(String[] args) {
// Start a try-catch block
try {
// Initialize the new objects
FileWriter fw = new FileWriter("FirstNames");
BufferedWriter bw = new BufferedWriter(fw);
// Create a String array to store the first names
String names[] = new String[] { "Hussain", "Ronald", "John", "James", "Robert", "Michael", "William", "David",
"Joseph", "Daniel" };
// Output the first names in the textfile
for (int x = 0; x < 10; x++){
bw.write(names[x]);
bw.newLine();
}
bw.close();
fw.close();
// Catch any errors
} catch (Exception e) {
System.out.println("An error occured!");
}
// Experiencing issues starting from here:
// Create another try-catch block to read the file
try {
// Initialize the new objects
FileReader fr = new FileReader("FirstNames.txt");
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
// Start a while loop to output the line
while (line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
fr.close();
} catch (NullPointerException e1) { // I have put it to NullPointerException only to see the errors I'm getting for now
// System.out.println("An Error Occured!");
}
}
}
My Output: