Naga
Naga

Reputation: 2021

Lock file for writing in android

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)

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 ?

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();
                }

Upvotes: 2

Views: 2679

Answers (1)

Naga
Naga

Reputation: 2021

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();
                }

Upvotes: 4

Related Questions