【问题标题】:Java inputstream read twiceJava 输入流读取两次
【发布时间】:2019-07-15 04:00:17
【问题描述】:

我可以从输入流中读取第一行并将其存储到字符串变量中。然后我如何读取剩余的行并复制到另一个输入流以进一步处理。

        InputStream is1=null;
        BufferedReader reader = null;
        String todecrypt = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            todecrypt =  reader.readLine(); // this will read the first line
             String line1=null;
             while ((line1 = reader.readLine()) != null){ //loop will run from 2nd line
                 is1 = new ByteArrayInputStream(line1.getBytes()); 
             }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());

        }

        System.out.println("to decrpt str==="+todecrypt);

然后我将使用 is1 作为第二行的另一个输入流,并将我的示例文件发送到这里

sample file

【问题讨论】:

  • 请提供一些您尝试过的代码
  • 我发布了我尝试过的代码,你可以看看它。
  • 从输入流中读取第一行后,您可以将其处理给其他人阅读。不需要新的InputStream
  • @jerry Chin 我可以使用相同的 inputStream 发送另一个类并从第二行再次读取吗?

标签: java spring inputstream


【解决方案1】:

将 Jerry Chin 的评论扩展为完整答案:

你可以这样做

    BufferedReader reader = null;
    String todecrypt = null;
    try {
        reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        todecrypt =  reader.readLine(); // this will read the first line
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage());
    }

    System.out.println("to decrpt str==="+todecrypt);

    //This will output the first character of the second line
    System.out.println((char)inputStream.read());

您可以将 Inputstream 想象成一行字符。读取一个字符是删除行中的第一个字符。之后,您仍然可以使用 Inputstream 来读取更多字符。 BufferedReader 只是读取 InputStream,直到找到一个 '\n'。

【讨论】:

    【解决方案2】:

    因为您使用的是阅读器(BufferedReaderInputStreamReader),它们从原始流(inputStream 变量)中读取数据作为字符,而不是字节。因此,从阅读器原始流中读取第一行后,它将为空。这是因为阅读器会尝试填充整个字符缓冲区(默认情况下它是defaultCharBufferSize = 8192 字符)。所以你真的不能再使用原始流了,因为它已经没有数据了。您必须从现有阅读器中读取剩余的字符,并使用剩余数据创建一个新的 InputStream。下面的代码示例:

    public static void main(String[] args) throws Exception  {
        ByteArrayInputStream bais = new ByteArrayInputStream("line 1 \r\n line 2 \r\n line 3 \r\n line 4".getBytes());
        BufferedReader reader = new BufferedReader(new InputStreamReader(bais));
        System.out.println(reader.readLine());
        StringBuilder sb = new StringBuilder();
        int c;
        while ((c = reader.read()) > 0)
            sb.append((char)c);
        String remainder = sb.toString();
        System.out.println("`" + remainder + "`");
        InputStream streamWithRemainingLines = new ByteArrayInputStream(remainder.getBytes());
    }
    

    请注意,\r\n 不会丢失

    【讨论】:

      猜你喜欢
      • 2012-03-19
      • 2014-12-04
      • 2011-05-29
      • 2014-10-03
      • 2016-05-02
      • 1970-01-01
      • 1970-01-01
      • 2013-07-31
      相关资源
      最近更新 更多