【问题标题】:Java InputStream Assignment and Non Blocking ReadsJava InputStream 分配和非阻塞读取
【发布时间】:2021-01-03 18:05:26
【问题描述】:
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 完成非阻塞读取?

【问题讨论】:

  • InputStream 读取被阻塞。这里没有非阻塞读取。很难看出您期望这项任务会发挥什么魔力。不清楚你在问什么。
  • @MarquisofLorne 根据ByteArrayImputStream docs read() 不会阻止。
  • 当然,但是消耗整个流来填充ByteArrayInputStream 的行为没有留下任何其他人随后可以读取的内容:并且赋值仍然没有执行任何操作,Java 具有按值传递的语义.很难看出这里的实际目标是什么。例如,您可以只传递实际的字节数组。可能的 XY 问题。
  • 只要public static void readSome(InputStream is) throws IOException { is.read(); is.read(); is.read(); },那么第一次调用会读取值1、2、3,而下一次调用会读取剩余的值4、5、6……

标签: java inputstream


【解决方案1】:

您的代码尝试使用 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.

    }
}

【讨论】:

    猜你喜欢
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多