Click here to Skip to main content
16,022,336 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Java
import java.io.*;

public class CreateFile1{
  public static void main(String[] args) throws IOException{
  File f;
  f=new File("myfile.txt");
  if(!f.exists()){
  f.createNewFile();
  System.out.println("New file \"myfile.txt\" has been created 
  to the current directory");
  }
  }
}



Can we lock this file with password. So that when anyone open this file in program or manually it should ask for password.
Posted
Updated 10-Feb-12 16:43pm
v2
Comments
CurrentlyBE 13-Feb-12 8:37am    
what does this do

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) {
}
CurrentlyBE 13-Feb-12 8:47am    
found another link

http://www.javabeat.net/tips/37-locking-files-using-java.html

check it out

1 solution

You can't. Certainly not in Java. To do this requires a shell extension to run on the end machine. The closest you can do, is to put it in a password protected zip.
 
Share this answer
 
v2
Comments
CurrentlyBE 10-Feb-12 13:06pm    
Really it can't happen disappointed by knowing this.
Christian Graus 10-Feb-12 13:12pm    
It seems obvious to me that your operating system, written in C, is going to open a txt file in the way that it always does, and there's no way to embedd Java code in a txt file, or to make the OS run it when someone tries to open that file.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900