Chinaunix首页 | 论坛 | 博客
  • 博客访问: 944608
  • 博文数量: 264
  • 博客积分: 10107
  • 博客等级: 上将
  • 技术积分: 2455
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-09 16:34
文章分类

全部博文(264)

文章存档

2012年(1)

2011年(11)

2010年(128)

2009年(82)

2008年(42)

我的朋友

分类: Java

2010-10-12 14:58:07

Convert a Java OutputStream to an InputStream

If you have ever programmed using Java IO, you will quickly run into a situation in which a class creates data on an OutputStream and you need to send it to another class that expects to read the data from an input stream. You'll soon be asking the question, "How do I convert an OutputStream to an InputStream?"

Nowhere in Java will you find a OutpStreamToInputStreamConverter class. Luckily, there are several ways to go about this.

Method 1: Buffer the data using a byte array

The easiest method is to buffer the data using a byte array. The code will look something like this:

  ByteArrayOutputStream out = new ByteArrayOutputStream();
  class1.putDataOnOutputStream(out);
  class2.processDataFromInputStream(
    new ByteArrayInputStream(out.toByteArray())
  );

That's it! The OutputStream has been converted to an InputStream.

Method 2: Use pipes

The problem with the first method is that you must actually have enough memory to buffer the entire amount of data. You could buffer larger amounts of data by using the filesystem rather than memory, but either way there is a hard limit to the size of the data that can be handled. The solution is create a thread to produce the data to the PipedOutputStream. The current thread can then read the data as it comes in.

  PipedInputStream in = new PipedInputStream();
  PipedOUtputStream out = new PipedOutputStream(in);
  new Thread(
    new Runnable(){
      public void run(){
        class1.putDataOnOutputStream(out);
      }
    }
  ).start();
  class2.processDataFromInputStream(in);

Method 3: Use Circular Buffers

The two piped streams in method two actually manage a hidden circular buffer. It is conceptually easier to use an explicit Circular Buffer. CircularBuffers offer several advantages:
  • One CircularBuffer class rather than two pipe classes.
  • It is easier to convert between the "buffer all data" and "extra threads" approaches.
  • You can change the buffer size rather than relying on the hard-coded 1k of buffer in the pipes.

Multiple Threaded Example of a Circular Buffer

  CircularByteBuffer cbb = new CircularByteBuffer();
  new Thread(
    new Runnable(){
      public void run(){
        class1.putDataOnOutputStream(cbb.getOutputStream());
      }
    }
  ).start();
  class2.processDataFromInputStream(cbb.getInputStream());

Single Threaded Example of a Circular Buffer

  // buffer all data in a circular buffer of infinite size
  CircularByteBuffer cbb = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE);
  class1.putDataOnOutputStream(cbb.getOutputStream());
  class2.processDataFromInputStream(cbb.getInputStream());

 
public String getPlotUrl() {
        log.debug("Creating a temporary Graph-File");
        ServletContext context = ( ServletContext ) getExternalContext().getContext();
        String realPath = context.getRealPath("/resources");
        File file = null;
        try {
            file = File.createTempFile( this.getHttpSession().getId(), ".png", new File( realPath ) );
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        file.deleteOnExit(  );
       
        OutputStream outs = null;
        try {
            outs = new BufferedOutputStream( new FileOutputStream( file ) );
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
       
        ChartGenerator cg = new ChartGenerator(this.getRequestBean());
        cg.createChart();
        try {
            cg.printChart( outs );
        } catch (IOException e) {
            e.printStackTrace();
        }
       
        try {
            outs.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        setPlotUrl( "/resources/" + file.getName());
       
        log.debug("Temp. File: " + this.plotUrl);
       
        return this.plotUrl;
    }
阅读(924) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~