java - 安卓 : nonwritablechannelException and ClosedChannelException

标签 java android

我正在使用FileLock,但不知道为什么总是遇到nonwritablechannelException异常:

public static List<String> 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;
}

当我从文件写入时遇到另一个异常:Exception ClosedChannelException

public static boolean saveToFile(Context ctx, List<String> 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;
    }

在 Android 开发者页面上,他们解释这个异常是:

A NonWritableChannelException is thrown when attempting to write to a channel that is not open for writing.

但我仍然无法解释为什么。请帮我弄清楚为什么我会遇到这个异常(exception)。

谢谢:)

最佳答案

"A NonWritableChannelException is thrown when attempting to write to a channel that is not open for writing."

您使用 openFileInput 打开了文件/ channel ...打开它是为了读取而不是写入。如果你想锁定文件,你必须使用 openFileOutput 打开它进行写入......或者也可以。

关于java - 安卓 : nonwritablechannelException and ClosedChannelException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16633654/

相关文章:

java - 将java路径永久设置为linux中的最新版本

java - 最终静态数组列表在函数中发生了变化

Java:用于显示差异的 GUI 组件?

java - Android单元测试: How do I test this?

android - Flutter,根据屏幕分辨率/dpi 优化 Material 尺寸的最佳方法?

java - JVM如何在运行时知道对象的类

android - kapt 发生异常 : java. lang.OutOfMemoryError: 超出 GC 开销限制

java - 是否可以从 Android 设备发送 HDMI CEC 命令。

android - Android 应用程序中的低功耗蓝牙

android - 无法连接远程调试器