本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
在 ContentStreamProvider
中實作 AWS SDK for Java 2.x
ContentStreamProvider
是 中使用的抽象, AWS SDK for Java 2.x 允許多次讀取輸入資料。本主題說明如何為您的應用程式ContentStreamProvider
正確實作 。
適用於 Java 的 SDK 2.x 每次需要讀取整個串流時都會使用 ContentStreamProvider#newStream()
方法。若要讓此項目適用於整個串流,傳回的串流必須一律位於內容的開頭,且必須包含相同的資料。
在下列各節中,我們提供三種方法來正確實作此行為。
使用 mark()
和 reset()
在下面的範例中,我們會在讀取開始之前mark(int)
在建構函數中使用 ,以確保我們可以將串流重設回開頭。對於每次叫用newStream()
,我們都會重設串流:
public class MyContentStreamProvider implements ContentStreamProvider { private InputStream contentStream; public MyContentStreamProvider(InputStream contentStream) { this.contentStream = contentStream; this.contentStream.mark(MAX_LEN); } @Override public InputStream newStream() { contentStream.reset(); return contentStream; } }
如果 mark()
和 reset()
無法使用,請使用緩衝
如果您的串流不支援 mark()
且reset()
直接支援 ,您仍然可以先在 中包裝串流,以使用先前顯示的解決方案BufferedInputStream
:
public class MyContentStreamProvider implements ContentStreamProvider { private BufferedReader contentStream; public MyContentStreamProvider(InputStream contentStream) { this.contentStream = new BufferedInputStream(contentStream); this.contentStream.mark(MAX_LEN); } @Override public InputStream newStream() { contentStream.reset(); return contentStream; } }
建立新的串流
更簡單的方法是在每次調用時,只取得資料的新串流,並關閉先前的串流:
public class MyContentStreamProvider implements ContentStreamProvider { private InputStream contentStream; @Override public InputStream newStream() { if (contentStream != null) { contentStream.close(); } contentStream = openStream(); return contentStream; } }