Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6029187
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T04:50:57+00:00 2026-05-23T04:50:57+00:00

Possible Duplicate: How can I lock a file using java (if possible) I have

  • 0

Possible Duplicate:
How can I lock a file using java (if possible)

I have two process that invoke two Java programs that modifying the same text file. I notice the content of the text file is missing data. I suspect that when one java program obtain the write stream to the text file, I think it block the other java program from modifying it(like when you have a file open, you cant delete that file). Is there a way to work around this other than database? (not to say that db solution is not clean or elegant, just that we wrote lot of codes in manipulating this text file)

EDIT

It turns out that I made a mistake targeting the problem. The reason why, data in my text file is missing is because,

ProcessA: keep add rows of data to the text file

ProcessB: at the beginning, load all the rows of the text field into a List. It is then manipulate the contains of that list. At the end, ProcessB write the list back out, replacing the contain of the text file.

This work great in sequential process. But when running together, if ProcessA adding data to the file, during the time ProcessB manipulating the List, then when ProcessB write the List back out, whatever ProcessA just add, will be overrided. So my initial thought is before ProcessB write the List back out, sync the data between text file and the List. So when I write the List back out, it will contains everything. so here is my effort

public void synchronizeFile(){
    try {
        File file = new File("path/to/file/that/both/A/and/B/write/to");
        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
        FileLock lock = channel.lock(); //Lock the file. Block until release the lock
        List<PackageLog> tempList = readAllLogs(file);
        if(tempList.size() > logList.size()){
            //data are in corrupted state. Synchronized them.
            for(PackageLog pl : tempList){
                if(!pl.equals(lookUp(pl.getPackageLabel().getPackageId(), pl.getPackageLabel().getTransactionId()))){
                    logList.add(pl);
                }
            }
        }
        lock.release(); //Release the file
        channel.close();
    } catch (IOException e) {
        logger.error("IOException: ", e); 
    }
}

So logList is the current List that ProcessB want to write out. So before the write out, I read the file and store data into tempList, if tempList and logList are not the same, sync them. The problem is that at this point, both ProcessA and ProcessB currently access the file, so when I try to lock the file, and read from it List<PackageLog> tempList = readAllLogs(file);, I either get OverlappingFileLockException, or java.io.IOException: The process cannot access the file because another process has locked a portion of the file. Please please help me fix this problem 🙁

EDIT2: My understand of Lock

public static void main(String[] args){
    File file = new File("C:\\dev\\harry\\data.txt");

    FileReader fileReader = null;
    BufferedReader bufferedReader = null;
    FileChannel channel = null;
    FileLock lock = null;
    try{
        channel  = new RandomAccessFile(file, "rw").getChannel();
        lock = channel.lock();
        fileReader = new FileReader(file);
        bufferedReader = new BufferedReader(fileReader);
        String data;
        while((data = bufferedReader.readLine()) != null){
            System.out.println(data);
        }
    }catch(IOException e){
        e.printStackTrace();
    }finally{
        try {
            lock.release();
            channel.close();
            if(bufferedReader != null) bufferedReader.close();
            if(fileReader != null) fileReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

and I got this error IOException: The process cannot access the file because another process has locked a portion of the file

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T04:50:58+00:00Added an answer on May 23, 2026 at 4:50 am

    So, you could use the method that Vineet Reynolds suggests in his comment.

    If the two processes are actually just separate Threads within the same application, then you could set a flag somewhere to indicate that the file is open.

    If it’s two separate applications/processes altogether, the underlying filesystem should lock the files. When you get an I/O error from your output stream, you should be able to wrap a try/catch block around that, and then set your app up to retry later, or whatever the desired behavior is for your particular application.

    Files aren’t really designed to be written to simultaneously by multiple applications. If you can maybe describe why you want to write to a file simultaneously from multiple processes, there may be other solutions that could be suggested.


    Updates after your recent edits:
    Ok, so you need at least 3 files to do what you’re talking about. You definitely cannot try to read/write data to a single file concurrently. Your three files are:

    1. the file that ProcessA dumps new/incoming data to
    2. the file that ProcessB is currently working on
    3. a final “output” file that holds the output from ProcessB.

    ProcessB’s loop:

    • Take any data in file#2, process it, and write the output to file#3
    • Delete file#2
    • Repeat

    ProcessA’s loop:

    • Write all new, incoming data to file#1
    • Periodically check to see if file#2 exists
    • When file#2 is deleted by ProcessB, then ProcessA should stop writing to file#1, rename file#1 to be file#2
    • Start a new file#1
    • Repeat
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: How can I convert my java program to an .exe file ?
Possible Duplicate: Can we change the device time using an application? is that possible
Possible Duplicate: How can I write a Java application that can update itself at
Possible Duplicate: How does @synchronized lock/unlock in Objective-C? I have an application that creates
Possible Duplicate: How can I find the method that called the current method? I
Possible Duplicate: How can I lock the first row and first column of a
Possible Duplicate: Can a JavaScript object have a prototype chain, but also be a
Possible Duplicate: Can't remove Default.png? I am using Xcode 4, but I am sure
Possible Duplicate: How do I lock a file in Perl? Does anyone know how
Possible Duplicate: Can we run Java applictions on iPhone? Does IPhone4 supports Java? Can

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.