3

我正在尝试优化以下代码,该代码用于生成包含从服务器流式传输到客户端的给定长度的随机数据的流:

@GET
@Path("/foo/....")
public Response download(...)
        throws IOException
{
    ...
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // This method writes some random bytes to a stream.
    generateRandomData(baos, resource.length());

    System.out.println("Generated stream with " +
                       baos.toByteArray().length +
                       " bytes.");

    InputStream is = new ByteArrayInputStream(baos.toByteArray());

    return Response.ok(is).build();
}

上面的代码看起来很荒谬,因为它不适用于大数据,我知道,但我还没有找到更好的方法来写入响应流。有人可以告诉我正确的做法吗?

提前谢谢了!

4

1 回答 1

1

Create your own InputStream implementation defining read method to return random data :

public class RandomInputStream
        extends InputStream
{

    private long count;

    private long length;

    private Random random = new Random();


    public RandomInputStream(long length)
    {
        super();
        this.length = length;
    }

    @Override
    public int read()
            throws IOException
    {
        if (count >= length)
        {
            return -1;
        }

        count++;

        return random.nextInt();
    }

    public long getCount()
    {
        return count;
    }

    public void setCount(long count)
    {
        this.count = count;
    }

    public long getLength()
    {
        return length;
    }

    public void setLength(long length)
    {
        this.length = length;
    }

}
于 2013-06-03T10:01:50.627 回答