我正在尝试优化以下代码,该代码用于生成包含从服务器流向客户端的给定长度的随机数据的流:
@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();
}
上面的代码看起来很荒谬,因为它不适用于大数据,我知道,但我还没有找到一种更好的方法来写入响应流。有人可以告诉我这样做的正确方法吗?
非常感谢提前!
答案 0 :(得分:1)
创建自己的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;
}
}