繁体   English   中英

Java InputStream读取两次

[英]Java inputstream read twice

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

        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作为第二行的另一个输入流,并将我的示例文件发送到此处

样本文件

将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'。

因为您使用的是读取器( BufferedReaderInputStreamReader ),所以它们以字符而不是字节的形式从原始流( inputStream变量)读取数据。 因此,从阅读器读取第一行后,原始流将为空。 这是因为阅读器将尝试填充整个char缓冲区(默认情况下为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不会丢失

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM