allow stopping a TypedInputStream on EOF

This commit is contained in:
Daniella 2024-06-13 16:34:53 +02:00
parent e65a448ac4
commit 84668c7e15
Signed by: TudbuT
GPG key ID: B3CF345217F202D3

View file

@ -1,5 +1,6 @@
package de.tudbut.io; package de.tudbut.io;
import java.io.EOFException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -12,7 +13,8 @@ public class TypedInputStream {
public int last = -1; public int last = -1;
private final Object waitForInputLock = new Object(); private final Object waitForInputLock = new Object();
private final Object readLock = new Object(); private final Object readLock = new Object();
private boolean stopOnEOF = false;
public InputStream getStream() { public InputStream getStream() {
return stream; return stream;
} }
@ -22,6 +24,11 @@ public class TypedInputStream {
public TypedInputStream(InputStream stream) { public TypedInputStream(InputStream stream) {
this.stream = stream; this.stream = stream;
} }
public TypedInputStream stopOnEOF() {
stopOnEOF = true;
return this;
}
public byte readByte() throws IOException { public byte readByte() throws IOException {
return (byte) read(); return (byte) read();
@ -141,16 +148,20 @@ public class TypedInputStream {
synchronized (waitForInputLock) { synchronized (waitForInputLock) {
if(last != -1) if(last != -1)
return; return;
while ((last = stream.read()) == -1) ; while ((last = stream.read()) == -1 && !stopOnEOF) ;
if(last == -1)
throw new EOFException();
} }
} }
public int read() throws IOException { public int read() throws IOException {
synchronized (readLock) { synchronized (readLock) {
synchronized (waitForInputLock) { synchronized (waitForInputLock) {
int i; int i;
if (last == -1) { if (last == -1) {
while ((i = stream.read()) == -1) ; while ((i = stream.read()) == -1 && !stopOnEOF) ;
if(i == -1)
throw new EOFException();
} }
else { else {
i = last; i = last;