Java - what is usual practice for simple reading from text files?
<p>I'm messing about with Java, after a long hiatus, and I'm running into my usual problems with its complexity.</p>

<p>I have what should be a simple problem, but what with InputStreams, InputReaders, and dealing with finally and close(), I'm not seeing an obvious answer.</p>

<p>I'm in the main() function of a simple command-line app.  I've parsed my command-line, and I have a input filename.  This contains either the path to a text file or "-", which means that the program should read from System.in.</p>

<p>What I want is a String containing the contents of the file (or the remaining contents of System.in).  And what I am ending up with is way too complex, so I'm looking for the simple way to do it.</p>

<p>Question 1: Given an InputStream (which might be System.in or it might be a FileInputStream() I opened myself, what's the simplest way to read all of its contents into a String?  The various readAll() methods I've been seeing returned byte arrays, for which there is a place, but it's not what I am looking for.</p>

<p>Question 2: What is the usual idiom for making sure that any reader I open will always be closed?</p>

<p>If I were writing in C++, I'd have put the close() in my class's destructor, and I'd be sure that close() would be called when my object fell out of scope.</p>

<p>If I were writing in C#, I'd have used a "using" block, and I'd have the same guarantee.</p>

<p>I'm sure this can be done in Java, but my attempts so far have seemed cumbersome.</p>

<p>If I try:</p>

<pre><code>try
{
    InputStream inStream = new InputStream(...);
}
finally
{
    inStream.close();
}
</code></pre>

<p>I get complains that "inStream cannot be resolved".</p>

<p>But if I try</p>

<pre><code>InputStream inStream = null;
try
{
    inStream = new InputStream(...);
}
finally
{
    if (inStream != null)
        inStream.close();
}
</code></pre>

<p>I get "Unhandled exception type IOException.</p>

<p>So now I'm at:</p>

<pre><code>InputStream inStream = null;
try
{
    inStream = new InputStream(...);
}
finally
{
    try
    {
        if (inStream != null)
            inStream.close();
    }
    catch (IOException ex)
    {
    }
}
</code></pre>

<p>And that just seems ludicrous.</p>

<p>What is the usual pattern?</p>
