下面列出了怎么用android.os.ParcelFileDescriptor.AutoCloseOutputStream的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public Void doInBackground(Void... args) {
try (final AutoCloseOutputStream os = new AutoCloseOutputStream(mPfd);
final SmbFile file = mClient.openFile(mUri, "r")) {
int size;
byte[] buf = new byte[mBuffer.capacity()];
while ((size = file.read(mBuffer, Integer.MAX_VALUE)) > 0) {
mBuffer.get(buf, 0, size);
os.write(buf, 0, size);
mBuffer.clear();
}
} catch (IOException e) {
Log.e(TAG, "Failed to read file.", e);
try {
mPfd.closeWithError(e.getMessage());
} catch (IOException exc) {
Log.e(TAG, "Can't even close PFD with error.", exc);
}
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode)
throws FileNotFoundException {
if ("r".equals(mode)) {
ParcelFileDescriptor[] pipe=null;
try {
pipe=ParcelFileDescriptor.createPipe();
new TransferOutThread(getInputStream(uri),
new AutoCloseOutputStream(pipe[1])).start();
}
catch (IOException e) {
Log.e(getClass().getSimpleName(), "Exception opening pipe", e);
throw new FileNotFoundException("Could not open pipe for: "
+ uri.toString());
}
return(pipe[0]);
}
throw new IllegalArgumentException("Cannot support writing!");
}