Question

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?

Was it helpful?

Solution 2

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top