I want to use single piece code which writes to a file if parameter is not null and otherwise uses standard output.
I have following snippet
val fileName: String = null
var writer: java.io.PrintWriter = null
if (fileName==null)
writer = new java.io.PrintWriter(System.out)
else
writer = new java.io.PrintWriter(new java.io.File(fileName))
writer.println("111")
writer.flush()
//writer.close()
System.out.println("222")
Everything works as expected but I was assuming in general case I need to close writer after using it . Please correct me if I'm wrong.
If however I uncomment writer.close()
then "222" is not pronted so looks like closing PrintWriter disables standard output.
Another question is how to rewrite code without var
.
UPDATE
Code without var
s can be like below (I intentionally did not use import
)
def getWriter(filename: String): java.io.PrintWriter = {
if (fileName==null)
new java.io.PrintWriter(System.out)
else
new java.io.PrintWriter(new java.io.File(fileName))
}
val writer = getWriter(fileName)
Yup. Don't close standard out.
You can wrap System.out to make the close call do nothing. In java, it'd look something like:
PrintStream closeIgnoringOut = new PrintStream(System.out) {
@Override public void close() {}
};
Even if filename
is a proper String
, it might not be a writable file.
def getWriter(filename: String): java.io.PrintWriter =
util.Try(new java.io.PrintWriter(new java.io.File(filename)))
.getOrElse(new java.io.PrintWriter(System.out){
override def close() = ()
})
This will default to System.out
if filename
fails for any reason.
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.