Search code examples
javafile-locking

Not able to write in self locked file


I have situation where file is being used by two processes. So I check my process if file is already locked then wait until is unlocked.

And once its unlocked by another process, I put up my lock then start reading and writing to the file. But am getting error like below. I know its a error because its locked by me, but I want to put lock on file first then start reading and writing so that other process could not use it till the time am using.

Exception in thread "main" java.io.IOException: The process cannot access the file because another process has locked a portion of the file

Here is my code snippet

package RestClient;
import java.io.*;
import java.nio.Buffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;

public class Filelocking {

       public static void main(String[] args) throws IOException {

              String Name = "E:\\RestAPI\\Token.txt";
              File File = new File(Name);
              File FileRename = new File(Name);

              boolean FileEdit = false;

              if (!File.renameTo(FileRename)) {

                     while (!File.renameTo(FileRename)) {
                           System.out.println("rename failed");

                           if (File.renameTo(FileRename)) {
                                  FileEdit = true;
                                  break;
                           }

                     }

              }

              else {

                     FileEdit = true;

              }

              System.out.println("rename success");

              if (FileEdit) {

                  RandomAccessFile AccessFile = new RandomAccessFile(File, "rw");
                  FileChannel channel = AccessFile.getChannel();

                     FileLock lock = null;
                     try {

                           lock = channel.lock();
                           System.out.println("Lock Status: " + lock.isValid());
                           BufferedReader read = new BufferedReader (new FileReader(File));

                           System.out.println( read.readLine());




                     }

                     catch (OverlappingFileLockException e) {

                           System.out.println("File Lock Error: " + e.getMessage());
                     }

                     lock.close();

              }

       }

}

Can anyone tell me please how can I fix this and what am doing wrong here ?


Solution

  • It's your own FileLock that's causing the problem. You should read your file from your FileLock.

    You should read it like this :

    ByteBuffer buffer = ByteBuffer.allocate(20);
    int noOfBytesRead = channel.read(buffer);
    

    You can find more info here

    If you want readline you could do :

    FileInputStream fin = new FileInputStream(file);
    if (FileEdit) {
    
        RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
        FileChannel channel = accessFile.getChannel();
    
            FileLock lock = null;
            try {
    
                lock = channel.lock();
                System.out.println("Lock Status: " + lock.isValid());
                InputStream is = Channels.newInputStream(channel);
                BufferedReader read = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    
                System.out.println(read.readLine());
    
            } catch (OverlappingFileLockException e) {
                  System.out.println("File Lock Error: " + e.getMessage());
            }
    
            lock.close();
    
        }
    

    As mentionned here