我正在尝试使用如下资源块在 try 中创建一个新的 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 对象的一个原因是因为我希望能够outFile
在我的类的其他方法中引用该对象。
看起来我不能用 try 来做资源,所以我在一个普通的 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();
}
}
我将演示使用 atry-with-resources
和调用另一个方法的首选方法,而不是尝试在构造函数中完成所有操作。即,将可关闭资源传递给其他方法。但我强烈建议您让此类资源的开启者负责关闭它们。喜欢,
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");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句