Java 多线程写文件

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用
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);

        }

    }

}

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:Linux下获取eth网卡MAC地址的代码

下一篇:IOS计算某个日期和当前时间的天数差