【问题标题】:PushbackInputStream - why existsPushbackInputStream - 为什么存在
【发布时间】:2014-05-06 10:00:44
【问题描述】:

为什么将字节推回流中是件好事? 当我处理流时,我可以忽略字节或者我可以修改它,如果我 想这样做:

    try(InputStream is = new FileInputStream("test.txt")){

        int aByte;
        char c;

        while((aByte = is.read()) != -1){

            c = (char)aByte;

            if(c == 'h') {
               c = 'X';
            }

            System.out.print(c);
        }

我检查了 javadocs,但我仍然不明白为什么在某些情况下我应该将数据放回流中。对不起,伙计们。

【问题讨论】:

    标签: pushbackinputstream


    【解决方案1】:

    push back 与向前窥视的选项有关,并测试某些条件是真还是假。如果为 false,您希望继续前进,就好像您没有提前达到峰值一样,因此您必须将流向后推,就像您往前看一样。否则你可以替换前面的峰部分并从那里继续。

    [见]http://tutorials.jenkov.com/java-io/pushbackinputstream.html

    [或]http://www.java-samples.com/showtutorial.php?tutorialid=390

    [或]书:“Herbert Schildt 的 The Complete Reference Part 2”。

    PushbackInputStream 旨在用于解析来自 InputStream 的数据。有时您需要提前读取几个字节以查看即将发生的内容,然后才能确定如何解释当前字节。 PushbackInputStream 允许您这样做。好吧,实际上它允许您将读取的字节推回流中。下次调用 read() 时将再次读取这些字节。 --詹科夫--

    int c; 
    while ((c = f.read()) != -1) { 
      switch(c) { 
      case '=': 
      if ((c = f.read()) == '=') {
        System.out.print(".eq."); 
      } else { 
        System.out.print("<-"); 
      f.unread(c); 
      } 
    }
    

    这样你就可以留在阅读的流程中。

    注意:PushbackInputStream 具有使用于创建它的 InputStream 的 mark( ) 或 reset( ) 方法无效的副作用。使用 markSupported( ) 检查您将使用 mark( )/reset( ) 的任何流。 --www.java-samples.com--

    【讨论】:

      猜你喜欢
      • 2016-12-31
      • 1970-01-01
      • 2021-12-10
      • 2010-11-12
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多