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/

相关文章:

java - 两次异步操作后更新 UI

javascript - 如果我传入参数,函数不会被异步调用

wpf - WPF异步验证的最佳做法?

java - 关于MediaPlayer.setDatasource(URL)的查询;

java - 为什么这个java代码返回负值,我怎样才能将它转换为delphi?

java - 检查两个字符串是否相同以停止输入

java - OGNL 无法调用构造函数

java - 抛出 OutOfMemoryError 是否会触发堆转储,或者内存实际上需要耗尽吗?

javascript - 如何聚合 Node.js 流回调中异步函数生成的 Promise?

C语言复制文件函数