我用Intellij写了两个工程,同时操作一个文件。一个工程将文件减锁,另外一个工程试图背文件中增加内容,两个工程的代码皆很短,以下:
1、锁文件
- 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();
- }
- }
[color=rgb(51, 102, 153) !important]赶钙代码
2、背文件种勾进内容
- 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);
- }
- }
[color=rgb(51, 102, 153) !important]赶钙代码
可是成绩去了,正在第一个工程将文件锁住的状况下,我仍旧可以用第两个工程背文件中胜利写进内容,那实刘么回事?
|