been pulling my hair out about this for ages!
Trying to put a lock on a text file (“test.txt”) then read a line from the text file and release the lock.
I get the following error:
“Err: java.io.IOException: The process cannot access the file because another process has locked a portion of the file”
See my code below:
public static void main(String[] args) throws Exception{
File file = new File("test.txt");
FileInputStream in = new FileInputStream(file);
DataInputStream dis = new DataInputStream(in);
FileChannel channel = new RandomAccessFile("test.txt", "rw").getChannel();
try{
FileLock lock = channel.tryLock();
System.out.println("Data: " + dis.readLine());
lock.release();
}catch(Exception ex){
System.out.println("Err: "+ex);
}
in.close();
}
It seems like a process is locking the file before it gets to the read operation?
Sorry for my ignorance, not been doing Java for long and ive tried looking for solutions elsewhere.
Thanks in advance!
try this: