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

3870 views java
-4

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

    }

What's wrong with the above code??

answered question

That isn't legal. try (PrintWriter outFile = new PrintWriter(filePath)) {

You might want to look at this question (stackoverflow.com/questions/13836486/…)

1 Answer

6

You can't refer resources opened in try block to instance variable,

this is one limitation of try with resource till java-9

But in java-9 you can happily use instance reference for resource opened in try block

Till java-8

try (PrintWriter outFile = new PrintWriter(filePath))

From java-9

 PrintWriter outFile;

public DataSummary(String filePath) {

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


enter code here

posted this

Have an answer?

JD

Please login first before posting an answer.