简体   繁体   中英

Java writing to File or System.out

I need to write characters to a file or to standard output. And I am curious if it could be done with one method.

Now I have something like this:

OutputStream out;    
if(toConsole)
   out = System.out;
else
   out = new FileOutputStream(file);

write(out);
}
void write (OutputStream str){
 ....
 str.write(string);

But it is a problem that I am using (in case when "str" is System.out) write instead print? (print java doc: "string's characters are converted into bytes according to the platform's default character encoding") In case if I would use PrintWriter(or PrintStream) as a parameter then i cannot use BufferedWriter and writing to the file would be slower.

It is possible to use a same code (and same methods) for writing to a file and to System.out? (This is for my school project so I want it to be a "pure" and fully correct)

What you're trying to accomplish, is to treat the fileoutput and the consoleoutput the same. This is possible, because System.out is a PrintStream , and you can create a PrintStream for a file like this

new PrintStream(yourFile) 

or insert a BufferedOutputStream in between

new PrintStream(new BufferedOutputStream(new FileOutputStream(yourFile))).

Note that this is not needed , because PrintStream does buffer its output itself .

I would create a variable (global or not), representing the current output. This might be a PrintStream , either System.out , or a PrintStream around a FileOutputStream , whatever you desire. You would then pass this stream to the write method or call the print methods on it directly.

The advantage is that you can easily switch this without much code modification, you can redirect it wherever you wan't. It's no problem to redirect it to a file and System.out ! You wouldn't get that pure flexibility with the way you're writing the method currently.

You could (not saying you should), also redirect System.out directly, using System.setOut . This however is bad style, because it is quite uncommon and might confuse everyone else, if they have not seen the call to System.setOut .

System.out is an object of type PrintStream. So yes, you can write to
System.out and/or to another file using exactly the same methods. Just
construct a PrintStream object and direct it to your file. So declare
your out variable as PrintStream to start with.

See also:

http://docs.oracle.com/javase/7/docs/api/java/lang/System.html

http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM