即使程序没有运行,也要扩展文件锁

时间:2018-03-15 13:09:17

标签: java filelock java.nio.file

我无法永久锁定文件。我的程序可以锁定文件,但是当我退出程序(程序没有运行)时,锁定将被释放。我想锁定文件,即使程序没有运行,是否可能?这是我的代码。请帮帮我

        import java.io.*;
        import java.nio.channels.FileChannel;
        import java.nio.file.FileSystems;
        import java.nio.file.Path;
        import javax.swing.JOptionPane;
        import static com.sun.nio.file.ExtendedOpenOption.NOSHARE_DELETE;
        import static com.sun.nio.file.ExtendedOpenOption.NOSHARE_READ;
        import static com.sun.nio.file.ExtendedOpenOption.NOSHARE_WRITE;
        import java.nio.channels.FileLock;

        public class LockFile {

            public static void ProcessPackageFiles2(File Path) {
                try {
                    File[] files = Path.listFiles();
                    for (File file : files) {
                        if (!file.isDirectory()) {
                            LockDown(file.getCanonicalPath());
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            public static void LockDown(String FilePath) {

                try {

                    Path path = FileSystems.getDefault().getPath(FilePath);
                    FileChannel locks = FileChannel.open(path, NOSHARE_WRITE, NOSHARE_DELETE, NOSHARE_READ);
                    FileLock fileLock = locks.tryLock();

                    if (fileLock != null) {
                        System.out.println("Locked");
                    } else {
                        JOptionPane.showMessageDialog(null, "FAILED");
                    }
                } catch (Exception ex) {
                    System.out.println(ex);
                }

            }

            public static void main(String[] args) {
                ProcessPackageFiles2(new File(path);
            }

this is the result when I run the program. The file will be unreadable and cannot be shared and deleted. But I want to extend it even the program is not running. But the question is HOW

0 个答案:

没有答案