读取InputStream两次以打印数据

时间:2017-06-08 14:23:10

标签: java

我正在尝试两次读取InputStream以将字节数和buf内容打印为String。我检查了inputStream,它是支持标记。因此我尝试使用mark()和重置方法来管理它 但我只是获取count的信息,而不是buf的信息。有没有解决方案可以解决这个问题?我无法使用org.apache.commons.io.IOUtils

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;


    public class Test {

        public static void main(String args[]) throws Exception {
            InputStream inputStream = null;
            ServerSocket serverSocket = new ServerSocket(27015);
            while (true) {
                Socket clientSocket = serverSocket.accept();
                inputStream = clientSocket.getInputStream();
                String byteData = Test.getBytes(inputStream, 512);
                System.out.println("byteData: " + byteData);

            }
        }


        public static String getBytes(InputStream is, int size) throws IOException {
            // Here I want to print the count and buff. Therefor I have to read the InputStream twice.
            if (is.markSupported()) {
                System.out.println("Mark is supported!"); // I am getting the output here also it is true.
            }

            // First read.
            byte[] temp = new byte[100];
            int count = is.read(temp); // here I am getting 9.
            System.out.println("count: " + count);
            is.mark(size);
            is.reset();

            // Second read: when the first read code is commented out. The buf has at the end [1, 0, 0, 0, 1, 0, 0, 0, 1]
            // otherwise it is empty in case the first read code is not commented out.
            int len;
            byte[] buf;

            if (is instanceof ByteArrayInputStream) {
                size = is.available();
                buf = new byte[size];
                len = is.read(buf, 0, size);
            } else {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                buf = new byte[size];
                while ((len = is.read(buf, 0, size)) != -1) {
                    bos.write(buf, 0, len);
                }
                buf = bos.toByteArray();
            }
            return "";
        }

    }

0 个答案:

没有答案