Java 多线程写文件

大家讲道理
大家讲道理 原创
2016-11-10 10:34:18 1432浏览
import java.io.File;
 
import java.io.IOException;
 
import java.io.RandomAccessFile;
 
import java.nio.channels.FileChannel;
 
import java.nio.channels.FileLock;
 
 
 
/**
 
 * @author DBJ
 
 *
 
 */
 
public class MyThreadInfoWritor {
 
 
    private String filename;
 
    /**
 
     *
 
     */
 
    public MyThreadInfoWritor(String fileName) {
 
        this.filename = fileName;
 
    }
 
 
    public void write(MyThreadInfo tInfo) {
 
 
        RandomAccessFile out = null;
 
        File file = new File(this.filename);
 
        try {
 
            if (!file.exists()) {
 
                file.createNewFile();
 
                out = new RandomAccessFile(file, "rw");
 
            }
 
            out = new RandomAccessFile(file, "rw");
 
 
            FileChannel fcout = out.getChannel();
 
            FileLock flout = null;
 
            while (true) {
 
                try {
 
                    flout = fcout.lock();
 
                    break;
 
                } catch (Exception e) {
 
                    System.out.println("其他线程正在操作该文件,当前线程休眠1000毫秒");
 
                    try {
 
                        Thread.sleep(1000);
 
                    } catch (InterruptedException e1) {
 
                        e1.printStackTrace();
 
                    }
 
                }
 
            }
 
 
            long fileLength = out.length();
 
             out.seek(fileLength);
 
            out.write(tInfo.toString().getBytes("utf8"));
 
 
            flout.release();
 
            fcout.close();
 
            out.close();
 
            out = null;
 
        } catch (IOException e) {
 
            file.deleteOnExit();
 
            System.out.println("Exception encountered: " + e);
 
        }
 
    }
 
}
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。