Is there a way to define a PrintWriter object in main() and use it in other methods (within the same class) without having to pass the object as a parameter to all of the other methods?

For example:

public static void main (String args []) throws FileNotFoundException {
      
          PrintWriter outFile = new PrintWriter("test.dat");
               doSomething();
               outFile.close();
      
 }

doSomething() {

         //do some computation here..

         outFile.println("print random crap....");

}

I tried declaring PrintWriter before main(), but that did not work either.

Thanks...

No, because it need to be checked for FileNotFoundException. So you can inplemented in it own class or just a method which will deal with printing request

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.