我正在使用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/