开发者

Java: Elegant way to print out text to Console or Text file

开发者 https://www.devze.com 2023-04-03 21:19 出处:网络
i\'ve a Java program that print out some text output. Actually my simple PrintOutput function is something like

i've a Java program that print out some text output. Actually my simple PrintOutput function is something like

System.out.println("some output");

But i would like to declare a variable

printonfile = true

to print my ou开发者_StackOverflowtput to a text file if setted to true, or to screen (console) if setted to false.

How can i assign the out to a file instead to System.out avoiding to make something like

 if (printonfile) {
   myfile.out("some output");
 }
 else {
   System.out.println("some output");
 }

Is there a way to declare an "output" variable at the beginning of my function so i can assign it the standard output (console) or a text file ?

Thanks


You've described a typical use case for the Strategy design pattern.

Create an interface Printer, make 2 implementations ConsolePrinter and FilePrinter, and use the correct one depending on the situation you have.

interface Printer {

   void print(String msg);
}

class ConsolePrinter implements Printer {

   public void print(String msg) {
      System.out.print(msg);
   }
}

class FilePrinter implements Printer {

   private final FileWriter fileWriter;

   public FilePrinter(File file) {
      this.fileWriter = new FileWriter(file); //here you should do some exceptions handling
   }

   public void print(String msg) {
      fileWriter.write(msg);   //here you should also care about exceptions
      fileWriter.flush();
   }
}

Printer chosenPrinter = printOnFile ? new FilePrinter(file) : new ConsolePrinter();
chosenPrinter.print("Hello");


You can do something like this:

    PrintSream stream = printToFile ? 
                        new PrintStream(new File(filename)) 
                        : System.out;

Now you can use stream wherever you want without any changes.


Look at a logging library e.g. log4j or java.util.logging to give very detailed control of output.


The out field of the System class is an instance of the PrintStream class; you can also construct a PrintStream object that outputs to a file. So your idea of setting up the output location could work as follows

PrintStream myOut = null;
// Decide output method somehow
if(...) {
  myOut = System.out;
}
else {
  myOut = new PrintStream(new File("/path/to/a/file"));
}

// Use the PrintStream to write a message
myOut.println("Hello World");

// Tidy up at end
myOut.close();


It will take a bit if time to properly set up, but log4j is definately worth a try if you want better/custom logging of your warnings, errors and general messages.

0

精彩评论

暂无评论...
验证码 换一张
取 消