文件锁

2019-06-13  本文已影响0人  张轻舟
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class WindowFileLock extends JFrame implements ActionListener{
    JTextArea text;
    JButton button;
    File file;
    RandomAccessFile input;
    FileChannel channel;
    FileLock lock;
    WindowFileLock(File f){
        file=f;
        try{
            input=new RandomAccessFile(file,"rw");
            channel=input.getChannel();
            lock=channel.tryLock();
        }
        catch(Exception exp){}
        text=new JTextArea();
        button=new JButton("读取一行");
        button.addActionListener(this);
        add(new JScrollPane(text),BorderLayout.CENTER);
        add(button,BorderLayout.SOUTH);
        setSize(300,400);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public void actionPerformed(ActionEvent e){
        try{
            lock.release();
            String lineString=input.readLine();
            text.append("\n"+lineString);
            lock=channel.tryLock();
            if(lineString==null)
                input.close();
            
            
            
        }
        catch(Exception ee){}
    }

}
import java.io.*;
public class Example_19 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        File file=new File("Example10_19.java");
        WindowFileLock win =new WindowFileLock(file);
        win.setTitle("使用文件锁");
        // TODO Auto-generated method stub

    }

}
上一篇下一篇

猜你喜欢

热点阅读