我正在尝试优化以下代码,该代码用于生成包含从服务器流式传输到客户端的给定长度的随机数据的流:
@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;
}
}
关于java - 如何正确使用 Jersey 的 Response.ok(inputStream) 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16893920/