Skip to content

Commit 5719ec2

Browse files
committed
新增:文件加锁
1 parent 4f44c5d commit 5719ec2

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package org.javacore.nio;
2+
3+
import java.io.FileNotFoundException;
4+
import java.io.FileOutputStream;
5+
import java.io.IOException;
6+
import java.nio.channels.FileLock;
7+
import java.util.concurrent.TimeUnit;
8+
9+
/*
10+
* Copyright [2015] [Jeff Lee]
11+
*
12+
* Licensed under the Apache License, Version 2.0 (the "License");
13+
* you may not use this file except in compliance with the License.
14+
* You may obtain a copy of the License at
15+
*
16+
* http://www.apache.org/licenses/LICENSE-2.0
17+
*
18+
* Unless required by applicable law or agreed to in writing, software
19+
* distributed under the License is distributed on an "AS IS" BASIS,
20+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
* See the License for the specific language governing permissions and
22+
* limitations under the License.
23+
*/
24+
25+
/**
26+
* @author Jeff Lee
27+
* @since 2015-10-15 19:31:34
28+
* 文件加锁
29+
*/
30+
public class FileLocking {
31+
public static void main(String[] args) throws IOException, InterruptedException {
32+
// 获取输出流
33+
FileOutputStream fos = new FileOutputStream("data.txt");
34+
// 从输出流中获取文件加锁对象,并锁定File
35+
FileLock fl = fos.getChannel().lock();
36+
if (fl != null) {
37+
System.out.println("Locked File");
38+
TimeUnit.MICROSECONDS.sleep(100);
39+
// 释放文件锁定
40+
fl.release();
41+
System.out.println("Release Lock");
42+
}
43+
}
44+
}

0 commit comments

Comments
 (0)