我收到一个我要保存到光盘的文件,这个文件具有最高优先级。但我想用另外两个操作“拆分”/“共享”这个流。
到目前为止,我的方法是拥有一个可以创建从MainStream中的缓冲区读取的子流的MainStream。
如果这是一种合适的方法,我需要一些方法来确定子流在流中的位置。我怎样才能做到这一点?
或者这是解决我主要问题的更好方法吗?
答案 0 :(得分: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
}
}
}
}