将字符添加到 BufferedInputStream 的末尾 java

Adding Character to the end of the BufferedInputStream java

我正在从 MimeMessage 获取输入流。在 InputStream 中,最后我想添加 \r\n.\r\n

表示消息结束。

请推荐。

只需将 InputStraem 值存储在一个字符串中,然后将其添加到该字符串:

    BufferedReader input;

    if(stream != null){
        input = new BufferedReader(new InputStreamReader(
                stream));
    String responseLine = "";
    String server_response = "";
    try {
        while (((responseLine = input.readLine()) != null) {
             server_response = server_response + responseLine  + "\r\n";
        }
    } catch (IOException e) {

    }
    server_response = server_response + "\r\n.\r\n";
  }

我错过了什么吗?还是您要求的?

您可以使用

即时附加它
public class ConcatInputStream extends InputStream {
    private final InputStream[] is;
    private int last = 0;

    ConcatInputStream(InputStream[] is) {
        this.is = is;
    }

    public static InputStream of(InputStream... is) {
        return new ConcatInputStream(is);
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        for (; last < is.length; last++) {
            int read = is[last].read(b, off, len);
            if (read >= 0)
                return read;
        }
        throw new EOFException();
    }

    @Override
    public int read() throws IOException {
        for (; last < is.length; last++) {
            int read = is[last].read();
            if (read >= 0)
                return read;
        }
        throw new EOFException();
    }

    @Override
    public int available() throws IOException {
        long available = 0;
        for(int i = last; i < is.length; i++)
            available += is[i].available();
        return (int) Math.min(Integer.MAX_VALUE, available);
   }
}

在你的情况下你可以这样做

InputStream in = 
InputStream in2 = ConcatInputStream.of(in, 
                              new ByteArrayInputStream("\r\n.\r\n".getBytes()));