Java输入流读取两次

问题描述 投票:3回答:2

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

        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作为第二行的anothor输入流,我的样本文件在这里发送

sample file

java spring inputstream
2个回答
0
投票

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


0
投票

因为您正在使用读者(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不会丢失

© www.soinside.com 2019 - 2024. All rights reserved.