54 lines
1.5 KiB
Java
54 lines
1.5 KiB
Java
package com.sheepit.client;
|
|
|
|
import lombok.NonNull;
|
|
|
|
import java.io.BufferedInputStream;
|
|
import java.io.FileInputStream;
|
|
import java.io.FileNotFoundException;
|
|
import java.io.IOException;
|
|
import java.io.InputStream;
|
|
import java.nio.file.Path;
|
|
import java.util.ArrayDeque;
|
|
import java.util.List;
|
|
import java.util.NoSuchElementException;
|
|
|
|
public class ChunkInputStream extends InputStream {
|
|
|
|
@NonNull private final ArrayDeque<Path> chunkPaths;
|
|
@NonNull private BufferedInputStream currentStream;
|
|
|
|
/**
|
|
* Given a list of chunk paths, provides an InputStream that reads the contents of these files in the order they were provided in.
|
|
* @param chunkPaths Non-empty, ordered list of paths
|
|
* @throws IOException If the first chunk could not be found. Errors with other chunk will be thrown during calls to read()
|
|
*/
|
|
public ChunkInputStream(List<Path> chunkPaths) throws IOException {
|
|
this.chunkPaths = new ArrayDeque<>(chunkPaths);
|
|
|
|
/// Setup the first chunk for reading
|
|
prepareNextChunk();
|
|
}
|
|
|
|
private void prepareNextChunk() throws FileNotFoundException, NoSuchElementException {
|
|
currentStream = new BufferedInputStream(new FileInputStream(chunkPaths.removeFirst().toFile()));
|
|
}
|
|
|
|
@Override public int read() throws IOException {
|
|
int result = currentStream.read();
|
|
|
|
if (result == -1) {
|
|
/// Finished reading from this chunk, continue with the next if possible
|
|
try {
|
|
prepareNextChunk();
|
|
}
|
|
catch (NoSuchElementException e) {
|
|
/// This was the last chunk
|
|
return -1;
|
|
}
|
|
result = currentStream.read();
|
|
}
|
|
|
|
return result;
|
|
}
|
|
}
|