Android : nonwritablechannelException and ClosedChannelException
<p>I'm using <code>FileLock</code>, but I don't know why I always meet <code>nonwritablechannelException exception</code> :</p>

<pre><code>public static List&lt;String&gt; readFromFile(Context ctx, String filename) {
        try {
            FileInputStream fis = ctx.openFileInput(filename);
            // lock this file
            FileLock lock = fis.getChannel().tryLock(); // Exception here
            // unlock this file
            lock.release();
            return null;
        } catch (Exception e) {
            Log.i(TAG, "Cannot read file");
            e.printStackTrace();
        }
        return null;
}
</code></pre>

<p>And I meet another exception when I writting from file: Exception <code>ClosedChannelException</code></p>

<pre><code>public static boolean saveToFile(Context ctx, List&lt;String&gt; lst, String filename) {
        try {
            FileOutputStream fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
            // lock this file
            FileLock lock = fos.getChannel().lock();
            PackageObject obj = new PackageObject(lst);
            ObjectOutputStream writer = new ObjectOutputStream(fos);
            writer.writeObject(obj);
            writer.close();
            // unlock this file
            lock.release(); // Exception at this line
                fos.close();
            return true;
        } catch (Exception e) {
            Log.i(TAG, "Cannot write file");
            e.printStackTrace();
        }
        return false;
    }
</code></pre>

<p>On Android Developer page, they explain this exception is:</p>

<blockquote>
  <p>A NonWritableChannelException is thrown when attempting to write to a
  channel that is not open for writing.</p>
</blockquote>

<p>But I still cannot explain why. Please help me figure out why I meet this exception please. </p>

<p>Thanks :)</p>
