java PrintWriter cannot be resolved

2019-05-09 10:26发布

问题:

I have no idea why I get the message "cannot be resolved" on out in eclipse on the 11th line

import java.io.*;
public class driver {
public static void main(String[] args) {
    try {
           PrintWriter out = new PrintWriter("output.txt");
        }
    catch (FileNotFoundException e) {
        System.out.print("file not found");
        e.printStackTrace();
    }
    out.print("hello");
    out.close();
    }

}

OK so now I have this

import java.io.*;
public class driver {
public static void main(String[] args) {
    PrintWriter out = null;
    try {
           out = new PrintWriter("output.txt");
        }
    catch (FileNotFoundException e) {
        System.out.print("file not found");
        e.printStackTrace();
    }
    out.print("hello");
    out.close();
  }
}

Why doesn't eclipse create a file once I close out?

回答1:

You can also use new try-with-resource block introduced in JDK 1.7, in this advantage is you don't need to worry about closing any resource which implements Closable Interface.

Then code will look like this:

try (PrintWriter out = new PrintWriter("output.txt"))
        {

            out.print("hello");
        }
        catch (FileNotFoundException e)
        {
            System.out.print("file not found");
            e.printStackTrace();
        }


回答2:

Declare your PrintWriter before the try block so it's scope isn't limited to the try block.