Java 如何使用Jersey';s Response.ok(inputStream)方法正确

Java 如何使用Jersey';s Response.ok(inputStream)方法正确,java,jersey,Java,Jersey,我正在尝试优化以下代码,该代码用于生成包含给定长度的随机数据的流,该数据从服务器流到客户端: @GET @Path("/foo/....") public Response download(...) throws IOException { ... ByteArrayOutputStream baos = new ByteArrayOutputStream(); // This method writes some random bytes to a

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

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

}

为什么您认为这对大数据不起作用
Response.ok(is).build()
看起来很简单。因为对于大型文件,我必须先将文件写入内存,然后再将其写入
InputStream
。但这不是JAX-RS的问题,而是数据如何生成的问题。Tichodroma,你确实是对的!