Skip to content

Instantly share code, notes, and snippets.

@AssIstne
Created May 11, 2018 08:18
Show Gist options
  • Save AssIstne/4461b3b6077a947e6e11cf2b8b2ec313 to your computer and use it in GitHub Desktop.
Save AssIstne/4461b3b6077a947e6e11cf2b8b2ec313 to your computer and use it in GitHub Desktop.
PipedInputStream和PipedOutputStream管道传输数据
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author assistne
* @since 2018/5/11
*/
public class Pipe {
private InputStream mInputStream;
private OutputStream mOutputStream;
private AtomicBoolean mIsOutClosed = new AtomicBoolean();
public Pipe(int size) {
mInputStream = new PipedInputStream(size);
try {
mOutputStream = new PipedOutputStream((PipedInputStream) mInputStream);
} catch (IOException e) {
// 不可能
/* no-op */
}
mIsOutClosed.set(false);
}
public boolean shouldReadInTo(byte[] temp) {
return canFullFill(temp) || mIsOutClosed.get();
}
public boolean canFullFill(byte[] container) {
try {
return mInputStream.available() >= container.length;
} catch (IOException e) {
return false;
}
}
public void write(byte[] data) throws IOException {
mOutputStream.write(data);
}
public int read(byte[] out) throws IOException {
return mInputStream.read(out);
}
public void close() {
closeOut();
closeIn();
}
public void closeIn() {
try {
mInputStream.close();
} catch (IOException e) {
/* no-op */
}
}
public void closeOut() {
try {
mOutputStream.close();
} catch (IOException e) {
/* no-op */
}
mIsOutClosed.set(true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment