处理输入流数据并有效地将其发送到输出流

时间:2015-09-23 06:43:21

标签: java inputstream outputstream

我目前正在制作一个基本的http代理,可以进行一些文本审查。 当我从输入流中读取时,我希望操纵字节数组的文本(即替换或删除)并将其传输到客户端的输出流。但是,来自服务器的输入流大小可能非常大(> 100MB)。有没有办法有效地做到这一点?

在从服务器读取数据并将数据发送到客户端时,这是我的代码段(不会操纵任何数据)。

int count = 0;
byte[] buffer = new byte[102400];
while ((count = fromServer.read(buffer)) > 0){
    System.out.println(new String(buffer, "UTF-8"));
    toClient.write(buffer, 0, count);
    fos.write(buffer, 0, count);
}
fos.close();
server.close();
client.close();

fromServer是来自服务器的输入流,fos是用于缓存目的的文件,toClient是客户端的输出流。

非常感谢!

1 个答案:

答案 0 :(得分:0)

我同意马特在这里。

没有缓冲,read()或readLine()的每次调用都可能导致从文件中读取字节,转换为字符,然后返回,这可能是非常低效的。

如果不操纵你的数据,我会建议以下

IOUtils.copy(inputStream, outputStream)

以下代码段可以帮助您处理数据

         FileOutputStream fos = new FileOutputStream(new File("c:\\output.xml"));
         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("c:\\input.xml")), 32*1024*1024);
         int bytesRead = -1;
         byte[] buffer = new byte[4096];
         while ((bytesRead = bis.read(buffer)) != -1) {
             String strFileContents = new String(buffer, 0, bytesRead);
             System.out.println(strFileContents);
            fos.write(buffer, 0, bytesRead);
         }
         fos.close();
         bis.close();

字符串中的操作很容易。

相关问题