<!DOCTYPE html><html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<p>Hello, I just wanted to share some information someone might find
interesting.<br>
</p>
<blockquote type="cite" cite="mid:13d1104b-3c9c-4000-96d9-8029bd300614@horstmann.com">PPPS.
Is it intended that print, println, input use System.getConsole()
under the hood? I am asking because the console potentially uses a
different character encoding than PrintStream and Scanner. </blockquote>
<p>I am not sure about the encoding, but <font face="monospace">System.console()</font>
may return <font face="monospace">null</font> if the input or
output are redirected.</p>
<blockquote>
<pre>java Main > output.txt
</pre>
</blockquote>
<p>If I use this command, <font face="monospace">System.console()</font>
would return <font face="monospace">null</font>, and the
following application would run into a <font face="monospace">NullPointerException</font>.</p>
<blockquote>
<pre>public final class Main {
public static void main(String[] args) {
System.console().readLine("Input: ");
}
}
</pre>
</blockquote>
<p>If you consider this issue, you may always want to use <font face="monospace">System.in</font> instead of <font face="monospace">System.console()</font>. However, if you look
at other (non-Java) applications, there is also another approach.
Let's consider the following command:<br>
</p>
<blockquote>
<pre>cat files.txt | sudo xargs -i cat {} > out 2> err
</pre>
</blockquote>
<p>With this command, <font face="monospace">sudo</font> will
prompt for your password on the Terminal, although neither STDIN,
STDOUT, nor STDERR is connected to the terminal. You can observe a
similar behavior with <font face="monospace">ssh</font>. I am not
aware of this being properly supported by Java. In Python, this is
implemented by the <a href="https://github.com/python/cpython/blob/6cd18c75a41a74cab69ebef0b7def3e48421bdd1/Lib/getpass.py">getpass
module</a> for Linux and Windows.</p>
<p>Note: Python has the unfortunate limitation that it does not have
a similar method for non-password-inputs. This causes users to mix
getpass(...) and input(...), causing inconsistent behavior. Here
is a <a href="https://stackoverflow.com/q/19661956">question on
StackOverflow</a> about the topic.<br>
</p>
<p>PS: I personally feel like Java could potentially benefit from
better utilities for interactive command line interfaces. However,
if this is something we want to implemented, we shouldn't only
think about beginners. Introducing a tiny separate world just for
beginners does not seem very desirable to me. Anyway, this is just
my personal take as a stranger. I just wrote this email because I
wanted to point out the details above.<br>
</p>
</body>
</html>