java PrintWriter cannot be resolved

感情迁移 提交于 2019-12-07 09:10:02

问题


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.



来源:https://stackoverflow.com/questions/22547086/java-printwriter-cannot-be-resolved

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!