Java InputStream 分配和非阻塞读取
Java InputStream Assignment and Non Blocking Reads
public class App {
public static void readSome(InputStream in) throws IOException {
ByteArrayInputStream is = new ByteArrayInputStream(in.readAllBytes());
is.read(); // variable number of non blocking reads
is.read();
is.read();
in = is; // this does nothing
}
public static void main(String[] args) throws IOException {
ByteArrayInputStream a = new ByteArrayInputStream(new byte[]{1, 2, 3, 4, 5, 6});
App.readSome(a);
//something
App.readSome(a); // should read 4, 5, 6
}
}
是否可以更改 readSome
方法中的代码,使 main 能够读取所有值,而 readSome 完成非阻塞读取?
您的代码尝试两次使用 ByteArrayInputStream - 这是不可能的。就是这样。
public class App {
public static void readSome(InputStream source) throws IOException {
byte[] bytes = source.readAllBytes(); // Reads (consumes) all your bytes from the source
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
is.read(); // variable number of non blocking reads
is.read();
is.read();
}
public static void main(String[] args) throws IOException {
ByteArrayInputStream source = new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, 5, 6 });
// source full
App.readSome(source);
// source fully consumed - so source is empty now
App.readSome(source); // cannot consume 4, 5, 6 - because source was already consumed.
}
}
public class App {
public static void readSome(InputStream in) throws IOException {
ByteArrayInputStream is = new ByteArrayInputStream(in.readAllBytes());
is.read(); // variable number of non blocking reads
is.read();
is.read();
in = is; // this does nothing
}
public static void main(String[] args) throws IOException {
ByteArrayInputStream a = new ByteArrayInputStream(new byte[]{1, 2, 3, 4, 5, 6});
App.readSome(a);
//something
App.readSome(a); // should read 4, 5, 6
}
}
是否可以更改 readSome
方法中的代码,使 main 能够读取所有值,而 readSome 完成非阻塞读取?
您的代码尝试两次使用 ByteArrayInputStream - 这是不可能的。就是这样。
public class App {
public static void readSome(InputStream source) throws IOException {
byte[] bytes = source.readAllBytes(); // Reads (consumes) all your bytes from the source
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
is.read(); // variable number of non blocking reads
is.read();
is.read();
}
public static void main(String[] args) throws IOException {
ByteArrayInputStream source = new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, 5, 6 });
// source full
App.readSome(source);
// source fully consumed - so source is empty now
App.readSome(source); // cannot consume 4, 5, 6 - because source was already consumed.
}
}