Liam
Liam

Reputation: 77

Java: PrintWriter object not detected

I am having some trouble getting java to recognize my PrintWriter object 'out'. I'm not really sure what the problem is.

public void storeInput(String fileName)
{
    String folderName = "C:/temper/testy/";

    File filetest = new File(folderName, fileName);

    System.out.println("ENTER TEXT!!!!!");
    String input = sc.nextLine();

    try {
        PrintWriter out = new PrintWriter(
                new BufferedWriter(
                new FileWriter(filetest)));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    out.println(filetest);

    out.close();


}

Upvotes: 1

Views: 752

Answers (3)

A4L
A4L

Reputation: 17595

PrintWriter out is visible only inside the try block. accessing it from outside will result in a compile error.

You can either move it's declaration outside the try block so that it become in you case visible in the hole body of the function storeInput but then you'll have to check whether ist is initialized before the statments

out.println(filetest);
out.close();

or better you move those tow statements in side the try block so when no exception accours out is always initialized.

For the close it is better to place it inside a finally block, that way you are always releasing resources no matter what exception happens.

public void storeInput(String fileName)
{
    String folderName = "C:/temper/testy/";

    File filetest = new File(folderName, fileName);

    System.out.println("ENTER TEXT!!!!!");
    String input = sc.nextLine();
    PrintWriter out = null;
    try {
        out = new PrintWriter(
                new BufferedWriter(
                        new FileWriter(filetest)));

        out.println(filetest);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if(out != null) {
            out.close();
        }
    }
}

Upvotes: 0

rgettman
rgettman

Reputation: 178263

The out variable's scope is currently only in the scope of the try block. Declare it before the try block so it's available after the block ends.

You'll need to initialize it to null so you don't get a "variable may not have been initialized" error. Then you'll need to test if it's null when attempting to use it past the try block.

Upvotes: 2

Adil Shaikh
Adil Shaikh

Reputation: 44740

declare that outside of try

PrintWriter out = null;
try {
      out = new PrintWriter(
                new BufferedWriter(
                new FileWriter(filetest)));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Upvotes: 2

Related Questions