Click here to Skip to main content
15,845,785 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have text file on server.
User can read it and write in it.
I want to put write lock on file when first user come and open it ,
If another user comes in between and open the file he should just read the file not allow to write in file.
Posted

1 solution

simplest approach:

Use a custom object "FileWithLock" instead of "File". You can simply set a lock on that one and react.

Java
import java.io.File;

public class FileWithLock extends File
{
    private boolean locked = false;
    public FileWithLock(String pathName){
    	super(pathName);
    }

    public void setLocked(boolean locked){
        this.locked = locked;
    }

    public boolean bisLocked(){
        return locked;
    }
}
 
Share this answer
 
Comments
hemant malpote 29-Oct-14 5:52am    
For second user new instance of file object will be create. So it will not comes in use.
It should be file specific. Like specific file is locked or not.
hemant malpote 29-Oct-14 6:03am    
I am trying with channel lock.
But the channel lock doesn't not allowing to read file as well.
I want only write lock not read .
TorstenH. 29-Oct-14 6:09am    
you mean like this?
http://www.java2s.com/Code/Java/File-Input-Output/DemonstratesfilelockingandsimplefilereadandwriteoperationsusingjavaniochannelsFileChannel.htm

It's a matter of design, how you approach this task.
hemant malpote 29-Oct-14 6:28am    
In this example they are reading file when there will be no lock . See the if condition 'if (lock != null)'
TorstenH. 29-Oct-14 6:10am    
It's a matter of design.
How do you access the file object?
How about a Hashmap holding the status?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900