Example of File Locking

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Example of File Locking

This is a example of Java program.

[edit] Java Source Code

  • Package: com.bruceeckel
  • File: FileLocking.java
package com.bruceeckel;
 
//: c12:FileLocking.java
//{Clean: file.txt}
//From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
//www.BruceEckel.com. See copyright notice in CopyRight.txt.
 
import java.io.FileOutputStream;
import java.nio.channels.FileLock;
 
public class FileLocking {
    public static void main(String[] args) throws Exception {
	FileOutputStream fos = new FileOutputStream("file.txt");
	FileLock fl = fos.getChannel().tryLock();
	if (fl != null) {
	    System.out.println("Locked File");
	    Thread.sleep(100);
	    fl.release();
	    System.out.println("Released Lock");
	}
	fos.close();
    }
}

[edit] What Result You Can Get

Run the program, you will get:


Locked File
Released Lock

[edit] Required External Library for this Java Example

Need nothing.


[edit] How to Run this Java Example Program

We recommend running this Java example program with Eclipse.

For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.

It's fairly easy.

Personal tools