2

我正在接收一个要保存到光盘的文件,它具有最高优先级。但我想用其他两个操作“拆分”/“共享”这个流。

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

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

4

1 回答 1

0

如果 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
        }
    }
}
}
于 2013-01-07T16:38:36.003 回答