Search code examples
javatry-catchprintwriter

PrintWriter object variable cannot resolve to type when used in try with resources


I'm trying to create a new PrintWriter object within a try with resources block as below, but it's giving me an error saying outFile cannot be resolved to a type:

public class DataSummary {

    PrintWriter outFile;

    public DataSummary(String filePath) {

        // Create new file to print report
        try (outFile = new PrintWriter(filePath)) {

        } catch (FileNotFoundException e) {
            System.out.println("File not found");
            e.printStackTrace();
        }

    }

EDIT:

A reason why I didn't want to declare the PrintWriter object within the try block is because I want to be able to reference the outFile object in other methods of my class.

It seems like I can't do it with try with resources, so I created it within a normal try/catch/finally block.

The text file is being created. However, when I try to write to file in another method, nothing seems to be printing in the text file, test.txt.

Why is this??

public class TestWrite {

  PrintWriter outFile;

  public TestWrite(String filePath) {

    // Create new file to print report
    try {
      outFile = new PrintWriter(filePath);
    } catch (FileNotFoundException e) {
      System.out.println("File not found");
      e.printStackTrace();
    } finally {
      outFile.close();
    }
  }

  public void generateReport() {
    outFile.print("Hello world");
    outFile.close();
  }
}

Solution

  • Instead of trying to do everything in a constructor, I will demonstrate the preferred way to use a try-with-resources and invoke another method. Namely, pass the closeable resource to the other method. But I strongly recommend you make the opener of such resources responsible for closing them. Like,

    public void writeToFile(String filePath) {
        try (PrintWriter outFile = new PrintWriter(filePath)) {
            generateReport(outFile);
        } catch (FileNotFoundException e) {
            System.out.println("File not found");
            e.printStackTrace();
        }
    }
    
    private void generateReport(PrintWriter outFile) {
        outFile.print("Hello world");
    }