2013-06-03 12 views
1

我在優化以下代碼,用於生成包含從服務器流式傳輸到客戶端的給定長度的隨機數據的流:如何正確使用Jersey的Response.ok(inputStream)方法

@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

爲什麼你認爲這不會對大數據的工作嗎? 'Response.ok(是).build()'看起來很容易。 – 2013-06-03 09:56:23

+0

因爲對於大文件,我必須在寫入'InputStream'之前將文件寫入內存。 – carlspring

+1

但這不是JAX-RS的問題,而是您的數據如何生成的問題。 – 2013-06-03 10:04:46

回答

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

} 
+0

輝煌,謝謝!我應該想到這個! – carlspring