簡體   English   中英

如何正確使用Jersey的Response.ok(inputStream)方法

[英]How to use Jersey's Response.ok(inputStream) method properly

我正在嘗試優化以下代碼,該代碼用於生成包含從服務器流向客戶端的給定長度的隨機數據的流:

@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();
}

上面的代碼看起來很荒謬,因為它不適用於大數據,我知道,但我還沒有找到一種更好的方法來寫入響應流。 有人可以告訴我這樣做的正確方法嗎?

提前謝謝了!

創建自己的InputStream實現,定義read方法以返回隨機數據:

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;
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM