|
3Java金币
我用Intellij写了两个工程,同时操纵一个文件。一个工程将文件加锁,另一个工程试图向文件中添加内容,两个工程的代码都很短,如下:
一、锁文件
- import java.io.*;
- import java.nio.channels.FileChannel;
- import java.nio.channels.FileLock;
- /**
- * Created by a on 16/4/4.
- */
- public class test{
- public static void main(String args[]) throws IOException {
- FileOutputStream fos = new FileOutputStream("buckets.config");
- FileChannel fc = fos.getChannel(); //获取FileChannel对象
- FileLock fl = fc.tryLock(); //or fc.lock();
- if(null != fl)
- System.out.println("You have got file lock.");
- //TODO write content to file
- //TODO write end, should release this lock
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String s = br.readLine();
- while (s != null) {
- br = new BufferedReader(new InputStreamReader(System.in));
- s = br.readLine();
- }
- fl.release(); //释放文件锁
- fos.close(); //关闭文件写操作
- // FileWriter fw = new FileWriter("buckets.config", true);
- // fw.append("tyiu" + "\n");
- // fw.flush();
- // fw.close();
- }
- }
复制代码 二、向文件中写入内容
- import java.io.BufferedWriter;
- import java.io.FileWriter;
- import java.io.IOException;
- /**
- * Created by a on 16/4/6.
- */
- public class test1 {
- public static void main(String args[]) throws IOException {
- FileWriter fw = new FileWriter("buckets.config");
- BufferedWriter bw = new BufferedWriter(fw);
- bw.write("asdfasdf");
- bw.flush();
- bw.close();
- fw.close();
- // String s = "";
- // s = s.substring(0, s.length()-1);
- // System.out.println(s);
- }
- }
复制代码
但是问题来了,在第一个工程将文件锁住的情况下,我仍然能够用第二个工程向文件中成功写入内容,这是怎么回事?
|
|