文件锁

作者: 张轻舟 | 来源:发表于2019-06-13 13:43 被阅读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
    
        }
    
    }
    

    相关文章

      网友评论

          本文标题:文件锁

          本文链接:https://www.haomeiwen.com/subject/aktsfctx.html