0

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:

Output

takendarkk
  • 3,347
  • 8
  • 25
  • 37
  • You have checked exceptions that you either have to `catch` or declare as `throws`. Note that your way of reading files is very old and cumbersome. Use NIO instead, simple one-liners... (Java 7+) – Zabuzard Oct 14 '20 at 20:37
  • Can't it has to be done this way –  Oct 14 '20 at 20:38
  • Fair. Still, the problem is not file io but you failing to understand exceptions. Read any tutorial about exceptions and you can fix your code. – Zabuzard Oct 14 '20 at 20:39
  • I tried but thats why I posted the question on here so I could get some help, although I did google this exception but could not find some good information –  Oct 14 '20 at 20:42
  • All exceptions that may occur must be caught – ABC Oct 14 '20 at 20:44
  • 2
    Does this answer your question? [Java unreported exception](https://stackoverflow.com/questions/2091589/java-unreported-exception) – takendarkk Oct 14 '20 at 20:45
  • 1
    Please paste your compiler errors into the question as text. – NomadMaker Oct 14 '20 at 20:57

1 Answers1

0

Your problem was you were writing FirstNames and then trying to read FirstNames.txt

I've made some enhancements below to use Try-with-resources which offers the benefit of not having to close the resource at the end of use.

I've also replaced the file name with a single variable that holds the string name. ("extract to variable" under your refactor menu in IntelliJ)

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

class Main {

    public static void main(String[] args) {
        // By deduplicating the filename you will remove the chance for errors.
        String fileName = "FirstNames";
        
        try (FileWriter fw = new FileWriter(fileName)) {
            // Initialize the new objects

            BufferedWriter bw = new BufferedWriter(fw);

            // should probably be a public static final String[] class field.
            String names[] = new String[]{"Hussain",
                    "Ronald",
                    "John",
                    "James",
                    "Robert",
                    "Michael",
                    "William",
                    "David",
                    "Joseph",
                    "Daniel"};

            // Output the first names in the textfile
            for (String name : names) {
                bw.write(name);
                bw.newLine();
            }
            bw.close();
        } catch (IOException ex) {
            ex.printStackTrace(); // read the stack trace to understand the errors
        }

        // Now TRY reading the file
        try (FileReader fr = new FileReader(fileName)){

            // Initialize the new objects
            BufferedReader br = new BufferedReader(fr);

            String line;
            // Start a while loop to output the line
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

            br.close();
            
        } catch (IOException e) {
            System.out.println("Catches errors related to br.readLine(), br.close() and new FileReader");
            e.printStackTrace();
        }
    }
}

Hopefully not too far removed from your original code that it still makes sense.

As others have mentioned, in a real-world situation, you may want to throw all/some errors higher up the call stack so they can be handled by a centralised error handler (so that all error handling logic is in one place rather than scattered all over the place).

At the moment I've just put ex.printStackTrace() and allowed execution to continue. This could result in multiple stack traces to be printed out which can be confusing.

Essentially start with the first error in the output and if you fix that, you may fix all the problems, otherwise re-run and look at the next first error in the console... and so on. Eventually when you've fixed all errors the code will run :)

Rob Evans
  • 2,822
  • 1
  • 9
  • 15