This topic describes how to download an object to a local computer.
Usage notes
Before you run the sample code in this topic, you must create an OSSClient instance by using methods such as using a custom domain name or Security Token Service (STS). For more information, see Initialization.
Examples
The following code provides an example on how to download a specific object to a local computer:
// Construct an object download request.
// Specify the name of the bucket and the full path of the object. In this example, the bucket name is examplebucket and the full path of the object is exampledir/exampleobject.txt. Do not include the bucket name in the full path.
GetObjectRequest get = new GetObjectRequest("examplebucket", "exampledir/exampleobject.txt");
oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
@Override
public void onSuccess(GetObjectRequest request, GetObjectResult result) {
// Start reading data.
long length = result.getContentLength();
if (length > 0) {
byte[] buffer = new byte[(int) length];
int readCount = 0;
while (readCount < length) {
try{
readCount += result.getObjectContent().read(buffer, readCount, (int) length - readCount);
}catch (Exception e){
OSSLog.logInfo(e.toString());
}
}
// Specify the full path of the downloaded object. Example: D:\\localpath\\exampleobject.jpg.
try {
FileOutputStream fout = new FileOutputStream("download_filePath");
fout.write(buffer);
fout.close();
} catch (Exception e) {
OSSLog.logInfo(e.toString());
}
}
}
@Override
public void onFailure(GetObjectRequest request, ClientException clientException,
ServiceException serviceException) {
}
});
References
For the complete sample code that is used to download an object to a local computer, visit GitHub.
For more information about the API operation that you can call to download an object to a local computer, see GetObject.
For more information about how to initialize an OSSClient instance, see Initialization.