栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

用Java的并行线程写入文件的最佳方法是什么?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用Java的并行线程写入文件的最佳方法是什么?

您的基本方法看起来不错。我将代码结构如下:

import java.io.BufferedWriter;import java.io.File;import java.io.IOException;import java.io.Writer;import java.util.concurrent.BlockingQueue;import java.util.concurrent.linkedBlockingQueue;import java.util.concurrent.TimeUnit;public interface FileWriter {    FileWriter append(CharSequence seq);    FileWriter indent(int indent);    void close();}class AsyncFileWriter implements FileWriter, Runnable {    private final File file;    private final Writer out;    private final BlockingQueue<Item> queue = new linkedBlockingQueue<Item>();    private volatile boolean started = false;    private volatile boolean stopped = false;    public AsyncFileWriter(File file) throws IOException {        this.file = file;        this.out = new BufferedWriter(new java.io.FileWriter(file));    }    public FileWriter append(CharSequence seq) {        if (!started) { throw new IllegalStateException("open() call expected before append()");        }        try { queue.put(new CharSeqItem(seq));        } catch (InterruptedException ignored) {        }        return this;    }    public FileWriter indent(int indent) {        if (!started) { throw new IllegalStateException("open() call expected before append()");        }        try { queue.put(new IndentItem(indent));        } catch (InterruptedException ignored) {        }        return this;    }    public void open() {        this.started = true;        new Thread(this).start();    }    public void run() {        while (!stopped) { try {     Item item = queue.poll(100, TimeUnit.MICROSECONDS);     if (item != null) {         try {  item.write(out);         } catch (IOException logme) {         }     } } catch (InterruptedException e) { }        }        try { out.close();        } catch (IOException ignore) {        }    }    public void close() {        this.stopped = true;    }    private static interface Item {        void write(Writer out) throws IOException;    }    private static class CharSeqItem implements Item {        private final CharSequence sequence;        public CharSeqItem(CharSequence sequence) { this.sequence = sequence;        }        public void write(Writer out) throws IOException { out.append(sequence);        }    }    private static class IndentItem implements Item {        private final int indent;        public IndentItem(int indent) { this.indent = indent;        }        public void write(Writer out) throws IOException { for (int i = 0; i < indent; i++) {     out.append(" "); }        }    }}

如果你不希望在一个单独的线程来写(也许在测试?),你可以有一个实现

FileWriter
它要求
append
Writer
在调用者线程。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/497583.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号