锁定文件以在android中编写 [英] Lock file for writing in android
问题描述
我正在将一些数据存储在SD卡上的文件中,并从不同的线程读取同一文件.为了避免读写的竞争状况,我想在两种情况下都将文件锁定(读写)
I am storing some data on a file on SD card and reading the same file from different thread . To avoid race condition of reading and writing I want to lock the file in both the scenario (Reading and writing)
我有两个选择 1)我可以使用同步来做到这一点 2)我可以使用文件锁定
I have two options in my mind 1) I can do this using Synchronization 2) I can do this using File Lock
我应该选择哪个,为什么?哪一个内存效率更高?
Which one should I choose and why ? Which one is more memory efficient?
我知道同步方式,但是我不知道如何使用文件锁,所以有人可以告诉我使用文件锁的代码吗?
I know Synchronization way but I don't know how to use File Lock so can any one tell me the code for using file lock ?
我尝试了文件锁定,但是在android中不起作用,请查看代码. 感谢您的帮助
I tried with file lock but it is not working in android , please have a look at the code. Any help is appreciated
File syncDatafile = new File(file, "sync.txt");
FileInputStream fileInputStream = new FileInputStream(syncDatafile);
java.nio.channels.FileLock lock = fileInputStream.getChannel().lock();
try{
FileWriter writer = new FileWriter(syncDatafile, true);
writer.write(data);
writer.flush();
writer.close();
}catch(Exception ex){
ex.printStackTrace();
}finally{
lock.release();
fileInputStream.close();
}
推荐答案
对不起,这是我的错误,我使用了FileInputStream来读取文件.很抱歉,现在已解决
I am sorry guys it was my mistake I was using FileInputStream which is used for reading a file . I am so sorry, now it's fixed
File syncDatafile = new File(file, "sync.txt");
FileOutputStream fileoutputStream = new FileOutputStream (syncDatafile);
java.nio.channels.FileLock lock = fileInputStream.getChannel().lock();
try{
FileWriter writer = new FileWriter(syncDatafile, true);
writer.write(data);
writer.flush();
writer.close();
}catch(Exception ex){
ex.printStackTrace();
}finally{
lock.release();
fileInputStream.close();
}
这篇关于锁定文件以在android中编写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!