java 文件锁的简单实现

时间:2021-08-31 08:38:35

java  文件锁的简单实现

             java文件锁的功能,隐私文件及安全性的提升,实现起来不难,这里贴下实现代码:

 实例代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public class FileLocker {
  public static void main(String[] args) throws IOException {
    File f = new File("aaa.txt");
    System.out.println(getFileContent(f) + 1);// no lock
    FileLock lock = getFileLock(f);// lock
    System.out.println(getFileContent(f) + 2);
    lock.release();// lock release
    System.out.println(getFileContent(f) + 3);// no lock
  }
  /**
   * get file content.
   *
   * @param file
   * @return
   */
  public static String getFileContent(File file) {
    String line = "";
    String content = "";
    try {
      BufferedReader bf = new BufferedReader(new InputStreamReader(
          new FileInputStream(file)));
      while ((line = bf.readLine()) != null) {
        content += line;
      }
    } catch (FileNotFoundException e) {
      content = "ERROR ";
    } catch (IOException e) {
      content = "ERROR ";
    }
    return content;
  }
  /**
   * get lock.
   *
   * @param file
   * @return
   * @throws IOException
   */
  public static FileLock getFileLock(File file) throws IOException {
    RandomAccessFile fi = new RandomAccessFile(file, "rw");
    FileChannel fc = fi.getChannel();
    return fc.tryLock();
  }
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!