Java create locked file

Creating a Java program that locks a file

This is my sample code. It doesn’t give me what I want. I want it to deny one access to read or to write the file, until I use my Java program to unlock it.

Java doesn’t allow to «lock» files, as some Operating Systems don’t have a file locking mechanism. If you want to do that, you’ll need to use a OS specific library (and won’t work on *nix, as unix doesn’t have this kind of file locking)

@augusto, u said i can use os specific library, am using windows 7, so can u give me a lead on how to go about it

What actually do you mean by ‘lock’ a file. Your question title sounds like you just want to prevent other programs from reading and writing to the file, however from what you’ve said what you really want is some form of encryption so that only your program can decrypt the file and make it usable again?

2 Answers 2

You can do this where you want to lock:

File f1 = new File(Your file path); f1.setExecutable(false); f1.setWritable(false); f1.setReadable(false); 

And for unlock you can just do this:

File f1 = new File(Your file path); f1.setExecutable(true); f1.setWritable(true); f1.setReadable(true); 

Before applying

Check if the file permission allow:

file.canExecute(); – return true, file is executable; false is not. file.canWrite(); – return true, file is writable; false is not. file.canRead(); – return true, file is readable; false is not. 

For a Unix system you have to put in this code:

Runtime.getRuntime().exec("chmod 777 file"); 

thanks for your prompt reply. but i still can read the file. What i want is something like a folder lock, denies one access to the folder once it is locked. But here am trying to do the same for file.

thanks alot, my file.canRead(); and file.canExecute(); are true, while file.canWrite(); is false. Is there any way to change all to false? mean while am gonna tick this question as answered.

You can lock the file by using Java code in a very simple way like:

Process p = Runtime.getRuntime().exec("chmod 755 " + yourfile); 

Here exec is a function which accepts a string value. You can put any command in that it will execute.

Or you can do it with another way like:

File f = new File("Your file name"); f.setExecutable(false); f.setWritable(false); f.setReadable(false); 

To be sure, check the file:

System.out.println("Is Execute allow: " + f.canExecute()); System.out.println("Is Write allow: " + f.canWrite()); System.out.println("Is Read allow: " + f.canRead()); 

Источник

Java create locked file

A token representing a lock on a region of a file. A file-lock object is created each time a lock is acquired on a file via one of the lock or tryLock methods of the FileChannel class, or the lock or tryLock methods of the AsynchronousFileChannel class. A file-lock object is initially valid. It remains valid until the lock is released by invoking the release method, by closing the channel that was used to acquire it, or by the termination of the Java virtual machine, whichever comes first. The validity of a lock may be tested by invoking its isValid method. A file lock is either exclusive or shared. A shared lock prevents other concurrently-running programs from acquiring an overlapping exclusive lock, but does allow them to acquire overlapping shared locks. An exclusive lock prevents other programs from acquiring an overlapping lock of either type. Once it is released, a lock has no further effect on the locks that may be acquired by other programs. Whether a lock is exclusive or shared may be determined by invoking its isShared method. Some platforms do not support shared locks, in which case a request for a shared lock is automatically converted into a request for an exclusive lock. The locks held on a particular file by a single Java virtual machine do not overlap. The overlaps method may be used to test whether a candidate lock range overlaps an existing lock. A file-lock object records the file channel upon whose file the lock is held, the type and validity of the lock, and the position and size of the locked region. Only the validity of a lock is subject to change over time; all other aspects of a lock’s state are immutable. File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine. File-lock objects are safe for use by multiple concurrent threads.

Platform dependencies

This file-locking API is intended to map directly to the native locking facility of the underlying operating system. Thus the locks held on a file should be visible to all programs that have access to the file, regardless of the language in which those programs are written. Whether or not a lock actually prevents another program from accessing the content of the locked region is system-dependent and therefore unspecified. The native file-locking facilities of some systems are merely advisory, meaning that programs must cooperatively observe a known locking protocol in order to guarantee data integrity. On other systems native file locks are mandatory, meaning that if one program locks a region of a file then other programs are actually prevented from accessing that region in a way that would violate the lock. On yet other systems, whether native file locks are advisory or mandatory is configurable on a per-file basis. To ensure consistent and correct behavior across platforms, it is strongly recommended that the locks provided by this API be used as if they were advisory locks. On some systems, acquiring a mandatory lock on a region of a file prevents that region from being mapped into memory , and vice versa. Programs that combine locking and mapping should be prepared for this combination to fail. On some systems, closing a channel releases all locks held by the Java virtual machine on the underlying file regardless of whether the locks were acquired via that channel or via another channel open on the same file. It is strongly recommended that, within a program, a unique channel be used to acquire all locks on any given file. Some network filesystems permit file locking to be used with memory-mapped files only when the locked regions are page-aligned and a whole multiple of the underlying hardware’s page size. Some network filesystems do not implement file locks on regions that extend past a certain position, often 2 30 or 2 31 . In general, great care should be taken when locking files that reside on network filesystems.

Constructor Summary

Method Summary

Источник

Java create locked file

A token representing a lock on a region of a file. A file-lock object is created each time a lock is acquired on a file via one of the lock or tryLock methods of the FileChannel class, or the lock or tryLock methods of the AsynchronousFileChannel class. A file-lock object is initially valid. It remains valid until the lock is released by invoking the release method, by closing the channel that was used to acquire it, or by the termination of the Java virtual machine, whichever comes first. The validity of a lock may be tested by invoking its isValid method. A file lock is either exclusive or shared. A shared lock prevents other concurrently-running programs from acquiring an overlapping exclusive lock, but does allow them to acquire overlapping shared locks. An exclusive lock prevents other programs from acquiring an overlapping lock of either type. Once it is released, a lock has no further effect on the locks that may be acquired by other programs. Whether a lock is exclusive or shared may be determined by invoking its isShared method. Some platforms do not support shared locks, in which case a request for a shared lock is automatically converted into a request for an exclusive lock. The locks held on a particular file by a single Java virtual machine do not overlap. The overlaps method may be used to test whether a candidate lock range overlaps an existing lock. A file-lock object records the file channel upon whose file the lock is held, the type and validity of the lock, and the position and size of the locked region. Only the validity of a lock is subject to change over time; all other aspects of a lock’s state are immutable. File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine. File-lock objects are safe for use by multiple concurrent threads.

Platform dependencies

This file-locking API is intended to map directly to the native locking facility of the underlying operating system. Thus the locks held on a file should be visible to all programs that have access to the file, regardless of the language in which those programs are written. Whether or not a lock actually prevents another program from accessing the content of the locked region is system-dependent and therefore unspecified. The native file-locking facilities of some systems are merely advisory, meaning that programs must cooperatively observe a known locking protocol in order to guarantee data integrity. On other systems native file locks are mandatory, meaning that if one program locks a region of a file then other programs are actually prevented from accessing that region in a way that would violate the lock. On yet other systems, whether native file locks are advisory or mandatory is configurable on a per-file basis. To ensure consistent and correct behavior across platforms, it is strongly recommended that the locks provided by this API be used as if they were advisory locks. On some systems, acquiring a mandatory lock on a region of a file prevents that region from being mapped into memory , and vice versa. Programs that combine locking and mapping should be prepared for this combination to fail. On some systems, closing a channel releases all locks held by the Java virtual machine on the underlying file regardless of whether the locks were acquired via that channel or via another channel open on the same file. It is strongly recommended that, within a program, a unique channel be used to acquire all locks on any given file. Some network filesystems permit file locking to be used with memory-mapped files only when the locked regions are page-aligned and a whole multiple of the underlying hardware’s page size. Some network filesystems do not implement file locks on regions that extend past a certain position, often 2 30 or 2 31 . In general, great care should be taken when locking files that reside on network filesystems.

Constructor Summary

Constructors
Modifier Constructor and Description
protected FileLock (AsynchronousFileChannel channel, long position, long size, boolean shared)

Method Summary

Источник

Put a lock on file

i access some files kept on server using my application. Multiple users can login into the application, i want to put some explicit lock on files that is opened by 1 of the user and want to release the lock when user either logs out or stop using the file. Any help how to do it? Thanks in advance

3 Answers 3

try < // Get a file channel for the file File file = new File("filename"); FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); // Use the file channel to create a lock on the file. // This method blocks until it can retrieve the lock. FileLock lock = channel.lock(); // Try acquiring the lock without blocking. This method returns // null or throws an exception if the file is already locked. try < lock = channel.tryLock(); >catch (OverlappingFileLockException e) < // File is already locked in this thread or virtual machine >// Release the lock lock.release(); // Close the file channel.close(); > catch (Exception e)

@ UNNI — wat in case of some1 doesnt reach lock.release() will the file be released i mean what if users session expires or he closes the browser what in those cases?

The scenario I think you are talking about is the file has been already locked by x user.In that case lock.release will not be executed because it will throw the exception. Now talking about session scope is how you want to relate this file handling mechanism while the user is in session scope.I think you put a lock for the file only if the user is valid and put into session.In other scanrio, this piece of code may not execute.This descision is based on your design.Third thing is when the user closed the browser then you can trap the event using javascript and send server side comand foraction

Источник

Читайте также:  quotes
Оцените статью