本文档介绍如何将OSS文件(Object)下载到本地文件。

以下代码用于把指定的OSS文件下载到本地文件:

//下载文件。
//objectKey等同于objectname,表示从OSS下载文件时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
GetObjectRequest get = new GetObjectRequest("BucketName", "objectKey");

oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
    @Override
    public void onSuccess(GetObjectRequest request, GetObjectResult result) {
//开始读取数据。
        long length = result.getContentLength();
        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());
            }
        }
//将下载后的文件存放在指定的本地路径。
        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)  {

    }
});