java - 异步流上的多个操作

标签 java asynchronous stream inputstream

我收到一个文件,我想将其保存到光盘中,该文件具有最高优先级。但我想与其他两个操作“拆分”/“共享”此流。

到目前为止,我的方法是拥有一个 MainStream,它可以创建从 MainStream 中的缓冲区读取的子流。

如果这是一种合适的方法,我需要一些方法来确定子流在流中的位置。我怎样才能做到这一点?
或者这是解决我的主要问题的更好方法?

最佳答案

如果 I/O 不是你的瓶颈,你可以使用多线程写入文件。

下面的代码只是一个例子:

/**
 * @author lichengwu
 * @version 1.0
 * @created 2013-01-08 12:11 AM
 */
public class MultiWrite {

private static final int SIZE = 1024 * 1024 * 1024;

ExecutorService exec = Executors.newFixedThreadPool(5);

public void start() {
    final File source = new File("");
    long size = source.length();
    final File store = new File("");

    for (long position = 0; position < size; position = position + SIZE) {
        exec.execute(new WriteTask(source, store, position));
    }

}

public class WriteTask implements Runnable {

    private final File store;

    private final File source;

    private final long position;

    public WriteTask(File source, File store, long position) {
        this.store = store;
        this.position = position;
        this.source = source;
    }

    public void run() {
        try {

            RandomAccessFile in = new RandomAccessFile(source, "r");

            // lock part of store
            RandomAccessFile out = new RandomAccessFile(store, "rw");
            FileChannel channel = out.getChannel();
            FileLock lock;
            while (true) {
                try {
                    lock = channel.tryLock(position, SIZE, false);
                    break;
                } catch (Exception e) {
                    // deal with
                }

            }

            out.seek(position);
            in.seek(position);
            byte[] data = new byte[SIZE];
            in.read(data);
            out.write(data);
            // release
            lock.release();
            channel.close();
            out.close();
            in.close();
        } catch (IOException e) {
            // deal with
        }
    }
}
}

关于java - 异步流上的多个操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14199415/

相关文章:

stream - 创建自定义标准输出流

java - 插入图像会丢失 PDF 内容

java - 排序数值的高效搜索

ios - 如何在 swift 3 中专门化通用高阶函数?

flutter - Flutter:传递CollectionReferece流

python - 如何在 Python 3 中将文本流编码为字节流?

java - 我可以将 jar 添加到 Maven 2 构建类路径而不安装它们吗?

java - 是什么导致了 java.lang.ArrayIndexOutOfBoundsException 以及如何防止它?

java - 用java的final关键字作弊

node.js - 如何在不阻塞父进程的 stdin 的情况下生成子进程?