PrintWriter 对象变量在尝试使用资源时无法解析为类型

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

我正尝试在 try with resources 块中创建一个新的 PrintWriter 对象,如下所示,但它给我一个错误 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();
        }

    }

编辑:

我不想在 try 块中声明 PrintWriter 对象的一个​​原因是我希望能够在 class 的其他方法中引用 outFile 对象。

似乎我不能用 try with resources 来做,所以我在一个普通的 try/catch/finally 块中创建了它。

正在创建文本文件。但是,当我尝试以另一种方法写入文件时,文本文件中似乎没有打印任何内容,test.txt

这是为什么?

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();
  }
}

我将演示使用 try-with-resources 并调用另一个方法的首选方法,而不是尝试在构造函数中执行所有操作。即,将 closeable 资源传递给另一个方法。但我强烈建议您让此类资源的开启者负责关闭它们。喜欢,

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");
}