英文:
Java InputStream Assignment and Non Blocking Reads
问题
以下是您要翻译的Java代码部分:
public class App {
public static void readSome(InputStream in) throws IOException {
ByteArrayInputStream is = new ByteArrayInputStream(in.readAllBytes());
is.read(); // 可变数量的非阻塞读取
is.read();
is.read();
in = is; // 这段代码无效
}
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); // 应该读取 4、5、6
}
}
请注意,代码中的注释和变量名未进行翻译,仅提供代码本身的翻译。
英文:
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
}
}
Is it possible to change the code in the readSome
method so that main is able to read all of the values, while readSome completes non blocking reads?
答案1
得分: 0
你的代码尝试两次消耗ByteArrayInputStream - 这是不可能的。就是这样。
public class App {
public static void readSome(InputStream source) throws IOException {
byte[] bytes = source.readAllBytes(); // 从源中读取(消耗)所有字节
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
is.read(); // 可变数量的非阻塞读取
is.read();
is.read();
}
public static void main(String[] args) throws IOException {
ByteArrayInputStream source = new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, 5, 6 });
// 源已满
App.readSome(source);
// 源已完全消耗 - 所以源现在为空
App.readSome(source); // 无法消耗4、5、6 - 因为源已经被消耗。
}
}
英文:
Your Code tries to consume the ByteArrayInputStream two times - this is impossible. And that's it.
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.
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论