Java输入流读取两次

Java输入流读取两次,java,spring,inputstream,Java,Spring,Inputstream,我可以从输入流中读取第一行并将其存储到字符串变量中,然后如何读取其余的行并复制到另一个输入流以进一步处理 InputStream is1=null; BufferedReader reader = null; String todecrypt = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { read

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

        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”。

因为您正在使用读卡器(
BufferedReader
InputStreamReader
),它们将原始流(
InputStream
变量)中的数据作为字符而不是字节读取。所以,在你们从读卡器中读取第一行之后,原始流将是空的。这是因为阅读器将尝试填充整个字符缓冲区(默认情况下,它是
defaultCharBufferSize=8192
chars)。所以你真的不能再使用原始流了,因为它已经没有数据了。您必须从现有读取器中读取剩余的字符,并使用剩余的数据创建一个新的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
并没有丢失

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