Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Writing to a file from multiple classes

807600Oct 16 2007 — edited Oct 24 2007
I am having trouble writing to a text file in my application. I have a class to write to the file:
public class writeText {
 public FileOutputStream out; 
 public PrintStream p; 

 public writeText() {
 }
 
 public void open(HttpServletRequest request) {
  HttpSession session = request.getSession(true);
  String filename="file.txt";
  try {
   out = new FileOutputStream(filename);
   p = new PrintStream(out);
  } catch (Exception e) { System.err.println("Error writing to file "+filename); }
 }
 
 public void print(String message) {
  p.println(message);
 }

 public static void main(String[] args) {
 }
}
My question is, how can I call 'print' from multiple classes?

I have created an instance of writeText in <Class1> and can open/write to the file, but if I try to write to it from <class2> I get a null pointer (as I haven't created an instance in this class). I know I could open it in each class and append to the file, but in some instances I cannot pass the request at the time I need it open it.

My aim is to be able to open the file as you start the application, then append to it from all the classes I have during the session. Am I going in the wrong direction with the code I have, and if so, can you please point me in the right direction.

Thanks.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 21 2007
Added on Oct 16 2007
6 comments
861 views