百度智能云

All Product Document

          Object Storage

          File Management

          Upload Files

          In BOS, the basic unit of data for user operations is object. object includes Key, Meta and Data. Key is the name of object. Meta is the user's description of the object and consists of a series of Name-Value pairs. Data is the data of the object.

          BOS Java SDK provides rich file upload interfaces, which can upload files in the following ways:

          • Simple Upload
          • Append Upload
          • Multipart Upload
          • Breakpoint Continued Upload

          Simple Upload

          BOS supports object upload in the forms of file, data stream, binary string and string in a simple upload, see the following codes,or Simple upload Demo:

          public void Putobject(BosClient client, String BucketName, String ObjectKey, byte[] byte1, String string1){ 
              // Access specified files. 
              File file = new File("/path/to/file.zip"); 
              // Access data stream. 
              InputStream inputStream = new FileInputStream("/path/to/test.zip"); 
          	
              // Upload object as file. 
              PutObjectResponse putObjectFromFileResponse = client.putObject(BucketName, ObjectKey, file); 
              // Upload object as the data stream. 
              PutObjectResponse putObjectResponseFromInputStream = client.putObject(BucketName, ObjectKey, inputStream); 
              // Upload object as the binary string. 
              PutObjectResponse putObjectResponseFromByte = client.putObject(BucketName, ObjectKey, byte1); 
              // Upload object as the character string. 
              PutObjectResponse putObjectResponseFromString = client.putObject(BucketName, ObjectKey, string1); 
          	
              // Print ETag. 
              System.out.println(putObjectFromFileResponse.getETag()); 
          } 

          Upload object to BOS in the file form. objects no more than 5 GB can be uploaded through Putobject. After the Putobject request is successfully processed, BOS will return the ETag of object as a file identifier in the Header.

          Set Object Metadata

          Object metadata is the attribute description of the file when the user uploads the file to BOS. It is mainly divided into two types: Set HTTP Headers and custom meta-information.

          • Set the Http Header of Object

          BOS Java SDK is to call the background HTTP interface in essence, so users can customize the Http Header of object when uploading files. Common http headers are described as follows:

          Name Description Default value
          Content-MD5 File data verification, BOS will enable MD5 verification of file content after setting. Comparing the MD5 you provided with the MD5 of the file, an error will be thrown if it is inconsistent. None
          Content-Type The MIME of the file defines the type of the file and the web page code, and determines the form and code in which the browser will read the file. If it does not indicate, BOS will automatically generate according to the file extension. If the file does not have an extension, the default value will be filled in. application/octet-stream
          Content-Disposition It instructs the MINME user agent how to display additional files, open or download, and file names. None
          Content-Length If the length of the uploaded file exceeds that of the stream/file, it will be cut; otherwise, it will be calculated as the actual value. Stream/File time length
          Expires Cache expiration time None
          Cache-Control It specifies the caching behavior of the web page when the object is downloaded. None
          x-bce-content-crc32 Upload CRC value (Cyclic Redundancy Check Code) of object. None

          The reference codes are as follows:

          // Upload input stream in initialization 
          ObjectMetadata meta = new ObjectMetadata(); 
          
          // Set the size of ContentLength. 
          meta.setContentLength(1000); 
          
          // Set ContentType. 
          meta.setContentType("application/json"); 
          
          // Set cache-control. 
          meta.setCacheControl("no-cache"); 
          
          // Set x-bce-content-crc32 
          meta.setxBceCrc("crc"); 
          
          client.putObject(BucketName, ObjectKey, content, meta); 
          • Custom Metadata

          Custom metadata is available under BOS for object description. As shown in the following code:

          // Set the name value of customized metadata as my-data. 
          meta.addUserMetadata("name", "my-data"); 
              
          // object uploading 
          client.putObject(BucketName, ObjectKey, content, meta); 

          Tips

          • As for the above code, users have customized a metadata of which the name is "name" and the value is "my-data".
          • When users download this object, they can get metadata together.
          • One object possesses similar parameters, but the total size of User Meta bellows 2KB.

          Set Storage Type When Uploading Object

          BOS supports standard storage, infrequency storage and cold storage. Uploading object and storing it as a infrequency storage type can be realized by specifying StorageClass. The corresponding parameters of the three storage types are as follows:

          Storage type Parameter
          Standard storage STANDRAD
          infrequency storage STANDARD_IA
          Cold storage COLD

          Take infrequency storage as an example, the code is as follows:

          public void putObjectStorageClass(){ 
              PutObjectRequest request = new PutObjectRequest(BucketName, key, file); 
              request.withStorageClass(BosClient.STORAGE_CLASS_STANDARD_IA); 
              client.putObject(request); 
          } 

          Append Upload

          In the simple upload method introduced above, the objects created are of Normal type, and you cannot append, as it is inconvenient to use in scenarios where data copying is frequent, such as log, video monitoring and live video.

          For this reason, Baidu AI Cloud BOS specifically supports appendObject, namely, uploading files through append. The object created by the appendObject operation is of Appendable object. And you can append data to the object. appendObject size is 0-5G.

          The sample code uploaded through appendObject is as follows, Or refer to Append Upload Demo:

          public void appendObject(BosClient client, String BucketName, String ObjectKey, byte[] byte1, String string1) { 
                  // Access specified files. 
                  File file = new File("/path/to/file.zip"); 
                  // Access data stream. 
                  InputStream inputStream = new FileInputStream("/path/to/test.zip"); 
          
                  // Upload object as file. 
                  AppendObjectResponse appendobjectFromFileResponse = client.appendobject(BucketName, ObjectKey, file); 
                  // Upload object as the data stream. 
                  AppendObjectResponse appendObjectResponseFromInputStream = client.appendobject(BucketName, ObjectKey, inputStream); 
                  // Upload object as the binary string. 
                  AppendObjectResponse appendObjectResponseFromByte = client.appendobject(BucketName, ObjectKey, byte1); 
                  // Upload object as the character string. 
                  AppendObjectResponse appendObjectResponseFromString = client.appendobject(BucketName, ObjectKey, string1); 
          
                  // Print ETag. 
                  System.out.println(appendobjectFromFileResponse.getETag()); 
                  // Print NextAppendOffset. 
                  System.out.println(appendobjectFromFileResponse.getNextAppendOffset()); 
                  // Print ContentMd5.
                  System.out.println(appendobjectFromFileResponse.getContentMd5()); 
          
                  // For an example of appended upload, you need to add the location of the next append in the request. 
                  Long nextAppendOffset = appendobjectFromFileResponse.getNextAppendOffset(); 
                  AppendObjectRequest appendobjectFromFileRequest = new AppendObjectRequest(BucketName,ObjectKey,file); 
                  appendObjectFromFileRequest.setOffset(nextAppendOffset);
                  AppendObjectResponse appendobjectFromFileResponse = client.appendobject(appendobjectFromFileRequest); 
              } 

          Multipart Upload

          In addition to simple upload and append upload, BOS also provides another upload mode, namely, Multipart Upload. You can use Multipart Upload mode in the following application scenarios (but not limited to this), such as:

          • Breakpoint upload support is required.
          • The file to upload is larger than 5 GB.
          • The network conditions are poor, and the connection with BOS servers is often disconnected.
          • The file needs to be uploaded streaming.
          • The size of the uploaded file cannot be determined before uploading it.

          Next, the implementation of Multipart Upload is described step by step. Suppose you have a file with the local path of /path/to/file.zip , upload it through Multipart Upload to BOS for its large size.

          Or reference Multipart Upload Demo

          Initialize Multipart Upload

          Use the initiateMultipartUpload method to initialize a Multipart Upload event:

          // Start Multipart Upload. 
          InitiateMultipartUploadRequest initiateMultipartUploadRequest = 
                  new InitiateMultipartUploadRequest(BucketName, ObjectKey); 
          InitiateMultipartUploadResponse initiateMultipartUploadResponse = 
                  client.initiateMultipartUpload(initiateMultipartUploadRequest); 
              
          // Print UploadId. 
          System.out.println("UploadId: " + initiateMultipartUploadResponse.getUploadId()); 

          The returned result of initiateMultipartUpload contains UploadId . It is the unique identification to distinguish the Multipart Upload events. We will use it in later operations.

          • Initialization of Uploaded Infrequency Storage Object

          Initialize a Multipart Upload event of infrequency storage:

          public void putMultiUploadStorageClass(){ 
              InitiateMultipartUploadRequest iniReq = new InitiateMultipartUploadRequest(BucketName, key); 
              iniReq.withStorageClass(BosClient.STORAGE_CLASS_STANDARD_IA); 
              client.initiateMultipartUpload(iniReq); 
          } 
          • Initialization of Uploaded Cold Storage Object

          Initialize a Multipart Upload event of infrequency storage:

          public void putMultiUploadStorageClass(){ 
              InitiateMultipartUploadRequest iniReq = new InitiateMultipartUploadRequest(BucketName, key); 
              iniReq.withStorageClass(BosClient.STORAGE_CLASS_COLD); 
              client.initiateMultipartUpload(iniReq); 
          } 

          Upload in Parts

          Next, upload the file in parts.

          // Set each part to 5 MB. 
          final long partSize = 1024 * 1024 * 5L; 
              
          File partFile = new File("/path/to/file.zip"); 
              
          // Calculate the number of part. 
          int partCount = (int) (partFile.length() / partSize); 
          if (partFile.length() % partSize != 0){ 
              partCount++; 
          } 
              
          // Create a List to save the ETag and PartNumber uploaded in parts. 
          List<PartETag> partETags = new ArrayList<PartETag>(); 
              
          for(int i = 0; i< partCount; i++){ 
              // Get file stream. 
              FileInputStream fis = new FileInputStream(partFile); 
              
              // Skip to the beginning of each part. 
              long skipBytes = partSize * i; 
              fis.skip(skipBytes); 
              
              // Calculate the size of each part. 
              long size = partSize< partFile.length() - skipBytes ? 
                      partSize : partFile.length() - skipBytes; 
              
              // Create UploadPartRequest, and upload part. 
              UploadPartRequest uploadPartRequest = new UploadPartRequest(); 
              uploadPartRequest.setBucketName(BucketName); 
              uploadPartRequest.setKey(ObjectKey); 
              uploadPartRequest.setUploadId(initiateMultipartUploadResponse.getUploadId()); 
              uploadPartRequest.setInputStream(fis); 
              uploadPartRequest.setPartSize(size); 
              uploadPartRequest.setPartNumber(i + 1); 
              UploadPartResponse uploadPartResponse = client.uploadPart(uploadPartRequest); 
              
              // Save the returned PartETag to the List. 
              partETags.add(uploadPartResponse.getPartETag()); 
             
              // Close the file. 
              fis.close(); 
          } 

          The core of the above code is to call the UploadPart method to upload each part. Pay attention to the following points:

          • The UploadPart method requires that all but the last Part be larger than or equal to 5 MB. However, the Upload Part interface does not immediately verify the size of the Upload Part. It verifies only in case of Complete Multipart Upload.
          • To ensure no error occurs to data in the network transmission process, it is recommended that you use the Content-MD5 value returned by each part BOS to verify the correctness of the uploaded part data respectively after UploadPart. When all part data is combined into one object, it no longer contains the MD5 value.
          • Part numbers range from 1 to 10,000. If this range is exceeded, BOS will return the error code of InvalidArgument.
          • Every time you upload a Part, locate the stream to the location corresponding to the beginning of the uploaded part.
          • Every time a Part is uploaded, the returned result of BOS will contain a PartETag object. It is a combination of the Etag and the PartNumber of the uploaded part. It will be used in the next steps to complete Multipart Upload, so it needs to be saved. In general, these PartETag objects will be saved to the List.

          Complete Multipart Upload

          Complete the Multipart Upload as shown in the following code:

          CompleteMultipartUploadRequest completeMultipartUploadRequest = 
                  new CompleteMultipartUploadRequest(BucketName, ObjectKey, initiateMultipartUploadResponse.getUploadId(), partETags); 
              
          // Complete Multipart Upload. 
          CompleteMultipartUploadResponse completeMultipartUploadResponse = 
                  client.completeMultipartUpload(completeMultipartUploadRequest); 
              
          // Print the ETag of object. 
          System.out.println(completeMultipartUploadResponse.getETag()); 

          The partETags in the code above are list of partETag saved in the Step 2, and after receiving the list of Part submitted by the users, BOS verifies the validity of each data part one by one. When all data Parts are verified, BOS will combine these data parts into a complete object.

          Cancel Multipart Upload Event

          You can use the abortMultipartUpload method to cancel Multipart Upload.

          AbortMultipartUploadRequest abortMultipartUploadRequest = 
                  new AbortMultipartUploadRequest(BucketName, ObjectKey, uploadId); 
              
          // Cancel Multipart Upload. 
          client.abortMultipartUpload(abortMultipartUploadRequest); 

          Get unfinished Multipart Upload Event

          You can use the listMultipartUploads method to get unfinished Multipart Upload events in the bucket.

          ListMultipartUploadsRequest listMultipartUploadsRequest = 
              new ListMultipartUploadsRequest(BucketName); 
          
          // Get all upload events in the bucket. 
          ListMultipartUploadsResponse listing = client.listMultipartUploads(listMultipartUploadsRequest); 
              
          // Traverse all uploaded events. 
          for (MultipartUploadSummary multipartUpload : listing.getMultipartUploads()) { 
              System.out.println("Key: " + multipartUpload.getKey() + " UploadId: " + multipartUpload.getUploadId()); 
          } 

          Note:

          1.By default, if the number of multipart upload event is more than 1,000, only 1,000 objects are returned, and the value of IsTruncated in returned result is True, and meanwhile, NextKeyMarker is returned as the starting point of the next reading. 2.To return more multipart upload events, you can use KeyMarker parameter for reading by time.

          Get All Uploaded Part Information

          You can use the listParts method to get all uploaded parts in an uploaded event.

          ListPartsRequest listPartsRequest = new ListPartsRequest(BucketName, ObjectKey, uploadId); 
              
          // Get information about all uploaded Parts. 
          ListPartsResponse partListing = client.listParts(listPartsRequest); 
              
          // Traverse all Parts. 
          for (PartSummary part : partListing.getParts()) { 
              System.out.println("PartNumber: " + part.getPartNumber() + " ETag: " + part.getETag()); 
          } 

          If you need to see the storage class of the object, use the following code:

          public void listPartsStorageClass(){ 
              ListResponse listPartsResponse = client.listParts(BucketName, key, uploadId); 
              String storageClass = listPartsResponse.getStorageClass(); 
          } 

          Note:

          1.By default, if the number of multipart upload event in bucket is more than 1,000, only 1,000 objects are returned, and the value of IsTruncated in returned result is True, and meanwhile, NextPartNumberMarker is returned as the starting point of the next reading. 2.To return more multipart upload events, you can use PartNumberMarker parameter for reading by time.

          Encapsulate Multipart Upload

          In Java SDK, BOS provides users with putSuperobjectFromFile interface, which encapsulates initiateMultipartUpload, UploadPart and completeMultipartUpload involved in multipart upload, and users only need to call the interface to complete multipart upload.

          File file = new File("/path/to/file.zip"); 
          PutSuperObjectRequest request = new PutSuperObjectRequest(BucketName, ObjectKey, file); 
          bosClient.putSuperobjectFromFile(request); 

          Where the parameters of PutSuperObjectRequest include:

          Parameter Description
          chunkSize The part size is 5MB by default
          nThreads The number of threads in thread pool in the process of multipart upload equals to number of cores of CPU by default
          isSuperobjectUploadCanced Whether to cancel multipart upload
          File upload file

          If a file takes a very long time, users can call the cancel() method in PutSuperObjectRequest and set isSuperobjectUploadCanced as true to cancel multipart upload.

          Breakpoint Continued Upload

          When a user uploads a large file to BOS, if the network is unstable or the program crashes, the entire upload fails, and the part uploaded before the failure is invalid, so the user has to start over again. This is not only a waste of resources, in the case of network instability, it cannot complete the upload even after multiple retries. Based on the above scenarios, BOS provides the ability to continue uploading at breakpoints:

          • Under normal network conditions, it is recommended to use the three-step upload method to divide the object into 5 MB part. Refer to Multipart Upload.
          • When you have a poor network condition, it is recommended to use appendobject method for breakpoint resume, and append a small data 256kb, please see Append upload

          Tips

          • Breakpoint continued upload is the encapsulation and enhancement of multipart upload. It is realized through multipart upload.
          • When the file is large or the network environment is poor, it is recommended to upload it in parts.

          Download File

          BOS Java SDK provides rich file download files, and users can download files from BOS in the following ways:

          • Simple streaming download
          • Download to local file
          • Breakpoint continued download
          • Range download
          • Download progress bar

          Please refer to Download files Demo

          Simple Streaming Download

          You can read object in a stream through the following codes:

          public void getobject(BosClient client, String BucketName, String ObjectKey) 
              throws IOException { 
          
              // Get object and return BosObject. 
              BosObject object = client.getobject(BucketName, ObjectKey); 
          
              // Get objectMeta. 
              ObjectMetadata meta = object.getObjectMetadata(); 
          
              // Get the input stream of object. 
              InputStream ObjectContent = object.getObjectContent(); 
          
              // Process object. 
              ...
          
              // Close stream. 
              ObjectContent.close(); 
          } 

          Note:

          1.BosObject contains information of object, including the bucket where the object is located, object name, MetaData and an input stream. You can read the contents of the object into files or memory by operating the input stream.
          2.ObjectMetadata contains ETag, Http Header ad custom metadata defined during upload of object.
          3.With the getObjectContent method of BosObject, it is also possible to obtain the input stream of returned object, and users can read this input stream to operate contents of object.

          Download Object to File

          You can download object to the specified file through the following code:

          // Create a GetObjectRequest. 
          GetObjectRequest getObjectRequest = new GetObjectRequest(BucketName, ObjectKey); 
              
          // Download object to file. 
          ObjectMetadata ObjectMetadata = client.getobject(getObjectRequest, new File("/path/to/file","filename")); 

          When the object is downloaded to the file using the above method, the method returns the ObjectMetadata object.

          Range Download

          For more features, you can specify the download range by using GetObjectRequest to achieve more refined object acquisition. If the specified download range is 0-100, the 0-100th (including) byte of data is returned, 101 bytes of data in total, i.e. [0, 100].

          // Create a GetObjectRequest. 
          GetObjectRequest getObjectRequest = new GetObjectRequest(BucketName, ObjectKey); 
          
          // Get data in the range of 0-100 bytes. 
          getObjectRequest.setRange(0, 100); 
          
          // Get object and return BosObject. 
          BosObject object = client.getobject(getObjectRequest); 

          With the setRange method of getObjectRequest, it is only possible to set the range of returned object. You can use this function for segmented download of file and breakpoint continued upload.

          Other Methods

          Get Storage Type of Object

          The storage class attributes of object are classified into STANDARD(standard storage), STANDARD_IA(infrequency storage) and COLD (cold storage). They can be implemented by the following code:

          public void getObjectStorageClass(){ 
              ObjectMetadata meta = client.getObjectMetadata(BucketName, key); 
              String storageClass = meta.getStorageClass(); 
          } 

          Get ObjectMetadata Only

          With getObjectMetadata method, it is possible to obtain ObjectMetadata only, without obtaining Objet entity. As shown in the following code:

          ObjectMetadata ObjectMetadata = client.getObjectMetadata(BucketName, ObjectKey); 

          Parameters available for calling in parsing class returned by getObjectMetadata include:

          Parameter Description
          contentType Type of object
          contentLength Size of object
          contentMd5 MD5 of object
          etag Entity tag of HTTP protocol for object
          storageClass Storage type of object
          userMetadata If userMetadata custom meta is specified in Putobject, return this item.
          xBceCrc If CRC value (cyclic redundancy check code) of object is specified in Putobject, this item is returned.

          Change File Storage Level

          As mentioned above, BOS supports assigning STANDARD (standard storage), STANDARD_IA (infrequency storage) and COLD (cold storage) to files. Meanwhile, BOS java SDK also supports users to change storage type for the specific files. The parameters involved are as follows:

          Parameter Description
          x-bce-storage-class Specify the storage type of object, STANDARD_IA for infrequency storage, COLD for cold storage; and when the type is not specified, it is standard storage by default.

          The following is an example:

          // Standard storage to infrequency storage 
          CopyObjectRequest copyObjectRequest = new CopyObjectRequest(srcBucketName, srcKey, destBucketName, destKey); 
          copyObjectRequest.setStorageClass("STANDARD_IA"); 
          client.copyobject(copyObjectRequest); 
          
          // infrequency storage to cold storage 
          CopyObjectRequest copyObjectRequest = new CopyObjectRequest(srcBucketName, srcKey, destBucketName, destKey); 
          copyObjectRequest.setStorageClass("COLD"); 
          client.copyobject(copyObjectRequest); 

          Get File Download URL

          The user can get the URL of the specified object by the following code:

          public String generatePresignedUrl(BosClient client, String BucketName, String ObjectKey, int expirationInSeconds) { 
          
             URL url = client.generatePresignedUrl(BucketName,<ObjectKey,<expirationInSeconds>); 
             //Specify name of bucket of object which users need to obtain, name of that object, time stamp and effective duration of URL   
          
              return url.toString(); 
          } 

          Note:

          • Before calling this function, the user needs to manually set endpoint as the domain name of the region. Baidu AI Cloud currently has opened access to multi-region support, please refer to Region Selection Instructions. Currently, it supports "North China-Beijing", "South China-Guangzhou" and "East China-Suzhou". Beijing: http://bj.bcebos.com; Guangzhou: http://gz.bcebos.com; Suzhou: http://su.bcebos.com
          • ExpirationInSeconds is the effective duration of the specified URL. It is an optional parameter calculated from the current time. When not configured, the default value of the system is 1,800 seconds. To set a time not invalid permanently, expirationInSeconds parameter can be set as -1, and it cannot be set as other negative numbers.
          • If the file expected to get is publicly readable, the corresponding URL link can be obtained through fast splicing of simple rules: http://BucketName.$region.bcebos.com/$bucket/$object

          Enumerate Files in Storage Space

          BOS SDK allows users to enumerate objects in the following two ways:

          • Simple enumeration
          • Complex enumeration by parameters

          In addition, you can simulate folders while listing files,Please refer to Listing documents Demo.

          Simple Enumeration

          When the user wants to simply and quickly enumerate the required files, the ListobjectsResponse object can be returned through the listobjects method, and the ListobjectsResponse object contains the returned result of this listobject request. You can access the description information of all objects through the getContents method in ListobjectsResponse.

          public void listobjects(BosClient client, String BucketName) { 
          
              // Access all object information of specified bucket. 
              ListobjectsResponse listing = client.listobjects(BucketName); 
          
              // Traverse all objects. 
              for (BosObjectSummary objectSummary : listing.getContents()) { 
                  System.out.println("ObjectKey: " + objectSummary.getKey()); 
              } 
          
          } 

          Note:

          1.By default, if the number of objects in bucket is more than 1,000, only 1,000 objects are returned, and the value of IsTruncated in the returned result is True, and NextMarker is returned as the starting point of the next reading. 2.To increase the number of returned objects, you can use the marker parameter to read by several times.

          Complex Enumeration by Parameters

          In addition to the simple listing above, users can realize various flexible inquiry functions by setting parameters of ListobjectsReques. Settable parameters of ListobjectsReques are as follows:

          Parameter feature Use mode
          Prefix The object key returned by the qualification must be prefixed with prefix. setPrefix(String prefix)
          Delimiter It is a character used to group object names. All names contain the specified prefix and appear for the first time. object between Delimiter characters as a set of elements: CommonPrefixes setDelimiter(String delimiter)
          Marker The set result returns from the first alphabetically sorted after the marker. setMarker(String marker)
          MaxKeys Limit the maximum number of objects returned this time, with a maximum of 1,000 and a default value of 1,000. If the specified value is greater than 1,000, operate as per 1,000. setMaxKeys(int maxKeys)

          Note:

          1.If an object is named with Prefix, when only Prefix is used for inquiry, all Keys returned still contain the object named with Prefix. 2.If an object is named with Prefix, when combination of Prefix and Delimiter is used for inquiry, all Keys returned contain Null, and the name of Key does not contain Prefix.

          Next, we use several cases to illustrate the method of parameter enumeration:

          Specify the Maximum Number of Returned Entries

          // Specify the maximum number of returned entries to be 500. 
          ListobjectsRequest listobjectsRequest = new ListobjectsRequest("BucketName"); 
          listobjectsRequest.withMaxKeys(500); 
          ListobjectsResponse listobjectsResponse = client.listobjects(listobjectsRequest); 
          for(BosObjectSummary objectSummary :listobjectsResponse.getContents()) { 
              System.out.println("ObjectKey:" + objectSummary.getKey()); 
          } 

          Return the Object with the Specified Prefix

          // Specify the returned object with test as the prefix. 
          ListobjectsRequest listobjectsRequest = new ListobjectsRequest("BucketName"); 
          listobjectsRequest.withPrefix("test"); 
          ListobjectsResponse listobjectsResponse = client.listobjects(listobjectsRequest); 
          for(BosObjectSummary objectSummary :listobjectsResponse.getContents()) { 
              System.out.println("ObjectKey:" + objectSummary.getKey()); 
          } 

          Return from the Specified Object

          // You can define an object not to be included, and return from it. 
          ListobjectsRequest listobjectsRequest = new ListobjectsRequest("BucketName"); 
          listobjectsRequest.withMarker("object"); 
          ListobjectsResponse listobjectsResponse = client.listobjects(listobjectsRequest); 
          for(BosObjectSummary objectSummary :listobjectsResponse.getContents()) { 
              System.out.println("ObjectKey:" + objectSummary.getKey()); 
          } 

          Page to Get all Objects

          // You can set a maximum of 500 records per page. 
          ListobjectsRequest listobjectsRequest = new ListobjectsRequest("BucketName"); 
          listobjectsRequest.withMaxKeys(500); 
          ListobjectsResponse listobjectsResponse; 
          boolean isTruncated = true; 
          while (isTruncated) { 
              listobjectsResponse = client.listobjects(listobjectsRequest); 
              isTruncated = listobjectsResponse.isTruncated(); 
              if (listobjectsResponse.getNextMarker() != null) { 
                  listobjectsRequest.withMarker(listobjectsResponse.getNextMarker()); 
              } 
          } 

          Page the Results after Getting All Specific Objects

          // You can set up to 500 records per page and get them from a specific object. 
          ListobjectsRequest listobjectsRequest = new ListobjectsRequest("BucketName"); 
          listobjectsRequest.withMaxKeys(500); 
          listobjectsRequest.withMarker("object"); 
          ListobjectsResponse listobjectsResponse; 
          boolean isTruncated = true; 
          while (isTruncated) { 
              listobjectsResponse = client.listobjects(listobjectsRequest); 
              isTruncated = listobjectsResponse.isTruncated(); 
              if (listobjectsResponse.getNextMarker() != null) { 
                  listobjectsRequest.withMarker(listobjectsResponse.getNextMarker()); 
              } 
          } 

          Page to Get the Object Results for All the Specified Prefixes

          // You can set the page to get the object with the specified prefix, with a maximum of 500 records per page. 
          ListobjectsRequest listobjectsRequest = new ListobjectsRequest("BucketName"); 
          listobjectsRequest.withMaxKeys(500); 
          listobjectsRequest.withPrefix("object"); 
          ListobjectsResponse listobjectsResponse; 
          boolean isTruncated = true; 
          while (isTruncated) { 
              listobjectsResponse = client.listobjects(listobjectsRequest); 
              isTruncated = listobjectsResponse.isTruncated(); 
              if (listobjectsResponse.getNextMarker() != null) { 
                  listobjectsRequest.withMarker(listobjectsResponse.getNextMarker()); 
              } 
          } 

          The parameters available for calling in parsing class returned by listobject method include:

          Parameter Description
          name bucket name
          prefix Match object starting from prefix to the Delimiter character of the first occurrence to return as a set of elements
          marker Starting point of this query
          maxKeys Maximum number of requests returned
          isTruncated It indicates whether all queries have returned; false means all results have been returned this time; true means all results have not been returned this time.
          contents Container of an object returned
          +key object name
          +lastModified Last time this object was modified
          +eTag HTTP protocol entity notes of object
          +storageClass Storage form of object
          +size Content size of object (number of bytes)
          +owner User information of bucket corresponding to object
          ++id User ID of bucket Owner
          ++displayName Name of bucket Owner

          Simulate Folder Feature

          No concept of folder exists in BOS storage results. All elements are stored in object, but BOS users often need folders to manage files when using data. Therefore, BOS provides the ability to create simulated folders, which essentially creates an object with size of 0. You can upload and download this object, but the console displays it as a folder for objects ending with "/".

          You can simulate the folder function through the combination of Delimiter and Prefix parameters. The combination of Delimiter and Prefix works like this:

          If setting Prefix to a folder name, you can list the files that begin with Prefix, that is, all the recursive files and subfolders (directories) under the folder. The file name is displayed in Contents. If Delimiter is set to "/" again, the return value only lists the files and subfolders (directories) under the folder. The names of subfiles (directories) under the folder are returned in the CommonPrefixes section, and the recursive files and folders under the subfolders are not displayed.

          Here are some application modes:

          List All Files in the Bucket

          When you need to get all files under bucket, refer to [Page to Get All objects](# Complex Enumeration by Parameters).

          Recursively List All Files in the Directory

          Set the Prefix parameter to access all files under a directory:

          // Create the request of ListobjectsRequest. 
          ListobjectsRequest listobjectsRequest = new ListobjectsRequest(BucketName); 
              
          // Recursively list all files in the fun directory. 
          listobjectsRequest.setPrefix("fun/"); 
              
          ListobjectsResponse listing = client.listobjects(listobjectsRequest); 
              
          // Traverse all objects. 
          System.out.println("objects:"); 
          for (BosObjectSummary objectSummary : listing.getContents()) { 
              System.out.println(objectSummary.getKey()); 
          	 } 
          } 

          Output:

          objects: 
          fun/ 
          fun/movie/001.avi 
          fun/movie/007.avi 
          fun/test.jpg 

          View Files and Subdirectories under the Directory

          The files and subdirectories under directory can be listed with the combination of Prefix and Delimiter:

          // Create the request of ListobjectsRequest. 
          ListobjectsRequest listobjectsRequest = new ListobjectsRequest(BucketName); 
              
          // '/' is a folder separator. 
          listobjectsRequest.setDelimiter("/"); 
              
          // List all files and folders under fun file directory. 
          listobjectsRequest.setPrefix("fun/"); 
              
          ListobjectsResponse listing = client.listobjects(listobjectsRequest); 
              
          // Traverse all objects. 
          System.out.println("objects:"); 
          for (BosObjectSummary objectSummary : listing.getContents()) { 
              System.out.println(objectSummary.getKey()); 
          } 
              
          // Traverse all CommonPrefix. 
          System.out.println("\nCommonPrefixs:"); 
          for (String commonPrefix : listing.getCommonPrefixes()) { 
              System.out.println(commonPrefix); 
          } 

          Output:

          objects: 
          fun/ 
          fun/test.jpg 
          
          CommonPrefixs: 
          fun/movie/

          In the result returned, the list in objectSummaries gives the files under fun directory. The list of CommonPrefixs gives all sub-folders under fun directory. It is clear that the fun/movie/001.avi file and fun/movie/007.avi file are not listed because they are movie directory of the fun folder.

          List the Storage Attributes of Objects in Bucket

          After uploading, if you need to view the storage class attribute of all objects in the specified bucket, you can use the following code:

          public void listobjectsStorageClass(){ 
              ListobjectsResponse listObjectResponse = client.listobjects("BucketName"); 
              List<BosObjectSummary> objectList = listObjectResponse.getContents(); 
              for(int i=0; i<objectList.length(); i++) { 
                  System.out.println(objectList[i].getStorageClass()); 
              } 
          } 

          Object Privilege Control

          Set Access Privilege of Object

          Currently BOS supports two ways to set ACL. The first method is to use Canned Acl. When PutObjectAcl, set access privilege of object through "x-bce-acl" or "x-bce-grant-privilege"' in header field. The currently set privileges include private and public-read, headers of these two types cannot appear in one request at the same time. The second is to upload an ACL file.

          For details, please see Set Object Privilege Control,Or view Demo Examples.

          1.Set access privilege of object by using "x-bce-acl" of header field or "x-bce-grant-privilege'

          • set object acl first mode (set by request header mode)
          SetObjectAclRequest setObjectAclRequest = new SetObjectAclRequest("yourBucketName","ObjectKey",CannedAccessControlList.PublicRead); 
          client.setObjectAcl(setObjectAclRequest); 
          • set object acl first mode (set xBceGrantRead by request header mode)
          String xBceGrantRead = "id=\"user_id1\""+",id=\"user_id2\""; 
          SetObjectAclRequest setObjectAclRequest = new SetObjectAclRequest(); 
          setObjectAclRequest.withBucketName("yourBucketName"); 
          setObjectAclRequest.withKey("ObjectKey"); 
          setObjectAclRequest.setxBceGrantRead(xBceGrantRead); 
          client.setObjectAcl(setObjectAclRequest); 
          • set object acl first mode (set xBceGrantFullControl by request header mode)
          String xBceGrantFullControl = "id=\"user_id1\""+",id=\"user_id2\""; 
          SetObjectAclRequest setObjectAclRequest = new SetObjectAclRequest(); 
          setObjectAclRequest.withBucketName("yourBucketName"); 
          setObjectAclRequest.withKey("ObjectKey"); 
          setObjectAclRequest.setxBceGrantFullControl(xBceGrantFullControl); 
          client.setObjectAcl(setObjectAclRequest); 

          2.Set object access privilege via setObjectAcl

          • set object acl second mode (json string)
          String jsonObjectAcl = "{\"accessControlList\":["+ "{\"grantee\":[{\"id\":\"*\"}], "+ "\"privilege\":[\"FULL_CONTROL\"]"+"}]}"; 
          
          SetObjectAclRequest setObjectAclRequest = new SetObjectAclRequest("yourBucketName","ObjectKey",jsonObjectAcl); 
          
          client.setObjectAcl(setObjectAclRequest); 
          • set object acl second mode, and users only need to specify the specified parameters.
          List<Grant> grants = new ArrayList<Grant>(); 
          List<Grantee> grantees = new ArrayList<Grantee>(); 
          List<privilege> privileges = new ArrayList<privilege>(); 
          
          // privilege to specific users 
          grantees.add(new Grantee("user_id1")); 
          grantees.add(new Grantee("user_id2")); 
          grantees.add(new Grantee("user_id3")); 
          
          // privilege setting 
          privileges.add(privilege.READ); 
          grants.add(new Grant().withGrantee(grantees).withprivilege(privileges)); 
          
          SetObjectAclRequest setObjectAclRequest = new SetObjectAclRequest("yourBucketName","ObjectKey", grants); 
          client.setObjectAcl(setObjectAclRequest); 

          View Object Privilege

          The following codes enable it to view object privilege:

          GetObjectAclRequest getObjectRequest = new GetObjectAclRequest(); 
          getObjectRequest.withBucketName("yourBucketName"); 
          getObjectRequest.withKey("ObjectKey"); 
          GetObjectAclResponse response = client.getObjectAcl(getObjectRequest); 

          The parameters available for calling in parsing class returned by getObjectAcl method include:

          Parameter Description
          accessControlList Identify privilege list of object
          grantee Identify authorized person
          -id Authorized person ID.
          privilege Identify the privilege of the authorized person.

          Delete Object Privilege

          The following codes enable it to delete object privilege:

          DeleteObjectAclRequest deleteObjectAclRequest = new DeleteObjectAclRequest("yourBucketName","ObjectKey"); 
          
          client.deleteObjectAcl(deleteObjectAclRequest); 

          Delete File

          The sample code can be referred to Delete File Demo

          Delete a Single File

          You can refer to the following code to delete an object:

          public void deleteobject(BosClient client, String BucketName, String ObjectKey) { 
          
              // Delete object. 
              client.deleteobject(BucketName,<ObjectKey);           //Specify the bucket name of the object to be deleted and the object name. 
          } 

          Delete Multiple Files

          Delete Multiple Files

          More objects can be deleted by reference to the following 2 methods:

          // 1.String in Json format 
          String jsonObjectKeys = "{\"objects\": ["+"{\"key\": \"token1.h\"},"+"{\"key\": \"token2.h\"}"+"]}"; 
          DeleteMultipleobjectsRequest request = new DeleteMultipleobjectsRequest(); 
          request.setBucketName("yourBucketName"); 
          request.setJsonDeleteobjects(jsonObjectKeys); 
          client.deleteMultipleobjects(request); 
          // 2.Users only need to specify the specified parameters 
          List<String> ObjectKeys = new ArrayList<String>(); 
          ObjectKeys.add("object1"); 
          ObjectKeys.add("object2"); 
          DeleteMultipleobjectsRequest request = new DeleteMultipleobjectsRequest(); 
          request.setBucketName("yourBucketName"); 
          request.setObjectKeys(ObjectKeys); 
          DeleteMultipleobjectsResponse response = client.deleteMultipleobjects(request); 

          Support in deleting up to 1,000 objects in one request. Message body does not exceed 2M. The message body returned only contains the object result in error during deletion; if all objects are deleted successfully, there is no message body.

          Check if the File Exists

          You can check whether a file exists through the following operations:

          // If true is returned, but false is not, other exceptions are thrown. 
          bool exists = client.doesobjectExist("BucketName", "ObjectKey"); 

          Get and Update Object Metadata

          Object metadata is the attribute description of files uploaded by users to BOS. It includes two types: HTTP Headers and User Meta.

          Get Object Metadata

          Refer to [ObjectMetadata Only](#Other Methods),or Demo.

          Modify Object Metadata

          BOS modifies object's metadata by copying object. That is, when copying object, set the destination bucket as the source bucket, set the destination object as the source object, and set a new Metadata to modify Metadata through copy. If the Metadata is not set, an error is reported.

            public void setobjectMeta(BosClient client, String BucketName, String ObjectKey, ObjectMetadata newObjectMetadata) { 
                  
                  CopyObjectRequest request = new CopyObjectRequest(BucketName, ObjectKey, BucketName, ObjectKey); 
          
                  // Create ObjectMetadata. 
                  request.setNewObjectMetadata(newObjectMetadata); 
          
                  // Copy object. 
                  CopyObjectResponse copyObjectResponse = client.copyobject(request); 
          
                  // Print results. 
                  System.out.println("ETag: " + copyObjectResponse.getETag() + " LastModified: " + copyObjectResponse.getLastModified()); 
              } 

          Copy File

          The sample code can be referred to Copy File Demo

          Copy File

          You can copy an object through the Copyobject function, as shown in the following code:

          public void copyobject(BosClient client, String srcBucketName, String srcKey, String destBucketName, String destKey) { 
              
              // Copy object. 
              CopyObjectResponse copyObjectResponse = client.copyobject(srcBucketName, srcKey, destBucketName, destKey); 
              
              // Print results. 
              System.out.println("ETag: " + copyObjectResponse.getETag() + " LastModified: " + copyObjectResponse.getLastModified()); 
          } 

          The copyobject method returns a 'CopyObjectResponse' object containing the ETag of the new object and the modification time.

          Copy Object through CopyObjectRequest

          You can also copy object through CopyObjectRequest. See the code below:

          // Initialize BosClient. 
          BosClient client = ...; 
              
          // Create CopyObjectRequest. 
          CopyObjectRequest copyObjectRequest = new CopyObjectRequest(srcBucketName, srcKey, destBucketName, destKey); 
              
          // Create Metadata. 
          Map<String, String> userMetadata = new HashMap<String, String>(); 
          userMetadata.put('<user-meta-key>','<user-meta-value>'); 
          ObjectMetadata meta = new ObjectMetadata();
          meta.setUserMetadata(userMetadata); 
          copyObjectRequest.setNewObjectMetadata(meta); 
              
          // Copy object. 
          CopyObjectResponse copyObjectResponse = client.copyobject(copyObjectRequest); 
              
          System.out.println("ETag: " + copyObjectResponse.getETag() + " LastModified: " + copyObjectResponse.getLastModified()); 

          You can modify the objectMeta of object through CopyObjectRequest and set MatchingETagConstraints parameters.

          Set the Copy Attribute of Object

          BOS provides a CopyObject interface to copy an existing Object to another Object, and in the process of copying, Etag or modification status of source Object is judged, and whether to execute copy is decided according to the judgment result. The following shows parameters in detail:

          Name Type Description Required or not
          x-bce-copy-source-if-match String If ETag value of source Object is equal to ETag provided by the user, copy operation is performed, otherwise the copy fails. No
          x-bce-copy-source-if-none-match String If ETag value of source Object is equal to ETag provided by the user, copy operation is performed, otherwise copy fails. No
          x-bce-copy-source-if-unmodified-since String If source Object is not modified after x-bce-copy-source-if-unmodified-since, copy operation is performed, otherwise copy fails. No
          x-bce-copy-source-if-modified-since String If source Object is modified after x-bce-copy-source-if-modified-since, copy operation is performed, otherwise copy fails. No

          Corresponding sample code:

          // Initialize BosClient
          BosClient client = ...;
          // Create CopyObjectRequest
          CopyObjectRequest copyObjectRequest = new CopyObjectRequest(srcBucketName, srcKey, destBucketName, destKey);
          // Create Metadata
          Map<String, String> userMetadata = new HashMap<String, String>();
          userMetadata.put("<user-meta-key>","<user-meta-value>");
                  
          meta.setUserMetadata(userMetadata);
          copyObjectRequest.setNewObjectMetadata(meta);
          //copy-source-if-match
          copyObjectRequest.withETag("111111111183bf192b57a4afc76fa632");
          //copy-source-if-none-match
          copyObjectRequest.withNoMatchingETagConstraint("111111111183bf192b57a4afc76fa632");
                  
          Date modifiedSinceConstraint = new Date();    
          SimpleDateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.UK);  
          df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));        
          String date = df.format(modifiedSinceConstraint);
          //copy-source-if-modified-since
          copyObjectRequest.withModifiedSinceConstraint(date);
          //copy-source-if-unmodified-since
          copyObjectRequest.withUnmodifiedSinceConstraint(date);
          CopyObjectResponse copyObjectResponse = client.copyObject(copyObjectRequest);
          System.out.println("ETag: " + copyObjectResponse.getETag() + " LastModified: " + copyObjectResponse.getLastModified());

          Synchronize Copy

          The Copyobject interface of the current BOS is implemented through synchronization. In synchronization mode, the BOS server returns successfully after Copy is completed. Synchronous copy can help users judge the copy status, but the copy time perceived by users will be longer, and the copy time is proportional to the file size.

          Synchronous Copy is more in line with industry conventions and improves compatibility with other platforms. Synchronous Copy also simplifies the business logic of BOS server and improves service efficiency.

          If you use SDK before bce-java-sdk-0.10.8 version, it is possible that the copy request is successful, but copy fails actually, so you are recommended to use the latest SDK version.

          Multipart Upload Copy

          In addition to copying files through Copyobject \x{2f1d}, BOS also provides another copy mode, namely, Multipart Upload Copy. You can use Multipart Upload Copy in the following application scenarios (but not limited to this), such as:

          • Breakpoint copy support is required.
          • The file to copy is larger than 5 GB.
          • Network conditions are poor, and connections to BOS services \x{fa38} are often disconnected.

          Next, the three-step copy will be introduced step by step.

          The three-step copy includes init, "Multipart Upload Copy" and complete. init and complete operate the same as Multipart Upload Copy.

          For ease of understanding, the following three steps are provided to copy the complete code:

          // Step 1: init 
          InitiateMultipartUploadRequest initiateMultipartUploadRequest = 
                  new InitiateMultipartUploadRequest("targetBucketName","targetObjectName"); 
          InitiateMultipartUploadResponse initiateMultipartUploadResponse = 
                  client.initiateMultipartUpload(initiateMultipartUploadRequest); 
          
          // Step 2: Multipart Upload Copy 
          long left_size=client.getObjectMetadata("sourceBucketName","sourceObjectName").getContentLength(); 
          long skipBytes = 0; 
          int partNumber = 1; 
          List<PartETag> partETags = new ArrayList<PartETag>(); 
          
          while (left_size > 0) { 
              long partSize = 1024 * 1024 * 1L; 
              if (left_size< partSize) { 
                  partSize = left_size; 
              } 
              UploadPartCopyRequest uploadPartCopyRequest = new UploadPartCopyRequest(); 
              uploadPartCopyRequest.setBucketName("targetBucketName"); 
              uploadPartCopyRequest.setKey("targetObjectName"); 
              uploadPartCopyRequest.setSourceBucketName("sourceBucketName"); 
              uploadPartCopyRequest.setSourceKey("sourceObjectName"); 
              uploadPartCopyRequest.setUploadId(initiateMultipartUploadResponse.getUploadId()); 
              uploadPartCopyRequest.setPartSize(partSize); 
              uploadPartCopyRequest.setOffSet(skipBytes); 
              uploadPartCopyRequest.setPartNumber(partNumber); 
              UploadPartCopyResponse uploadPartCopyResponse = client.uploadPartCopy(uploadPartCopyRequest); 
              // Save the PartETag returned to List. 
              PartETag partETag = new PartETag(partNumber,uploadPartCopyResponse.getETag()); 
              partETags.add(partETag); 
              left_size -= partSize; 
              skipBytes += partSize; 
              partNumber+=1; 
          } 
          
          // Step 3: complete 
          CompleteMultipartUploadRequest completeMultipartUploadRequest = 
                  new CompleteMultipartUploadRequest("targetBucketName", "targetObjectName", initiateMultipartUploadResponse.getUploadId(), partETags); 
          CompleteMultipartUploadResponse completeMultipartUploadResponse = 
                  client.completeMultipartUpload(completeMultipartUploadRequest); 

          Note:

          1.The offset parameter is the starting offset position of the part, in bytes.
          2.The size parameter defines the size of each part in bytes. Except for the last Part, all other Parts are larger than 5 MB.

          Select Files

          BOS Java SDK provides SelectObject interface, which is used to specify object to execute SQL statements in Bucket, select specified contents for return. Please refer to Select Object. Currently, the object types supported is CSV(including CSV files of TSV and other types) and JSON files: Please refer to Select File Demo for example codes

          • Select CSV file
          • Select JSON file

          Select CSV file

          Please refer to the following codes for Java SDK to select CSV file:

          final String csvContent = "header1,header2,header3\r\n" +
                                    "1,2,3.4\r\n" +
                                    "a,b,c\r\n" +
                                    "\"d\",\"e\",\"f\"\r\n" +
                                    "true,false,true\r\n" +
                                    "2006-01-02 15:04:06,2006-01-02 16:04:06,2006-01-02 17:04:06";
          client.putObject("bucketName", "test-csv", new ByteArrayInputStream(csvContent.getBytes()));
          SelectObjectRequest request = new SelectObjectRequest("bucketName", "test-csv")
                  .withSelectType("csv")                                   
                  .withExpression("select * from BosObject limit 3")
                  .withInputSerialization(new InputSerialization()
                          .withCompressionType("NONE")
                          .withFileHeaderInfo("NONE")
                          .withRecordDelimiter("\r\n")
                          .withFieldDelimiter(",")
                          .withQuoteCharacter("\"")
                          .withCommentCharacter("#"))
                  .withOutputSerialization(new OutputSerialization()
                          .withOutputHeader(false)
                          .withQuoteFields("ALWAYS")
                          .withRecordDelimiter("\n")
                          .withFieldDelimiter(",")
                          .withQuoteCharacter("\""))
                  .withRequestProgress(false);
          SelectObjectResponse response = client.selectObject(request);
          // Output the returned records 
          SelectObjectResponse.Messages messages = response.getMessages();
          while (messages.hasNext()) {
              SelectObjectResponse.CommonMessage message = messages.next();
              if (message.Type.equals("Records")) {
                  for (String record: message.getRecords()) {
                      System.out.println(record);
                  }
              }
          }

          Select the results output by CSV file:

          "header1","header2","header3"
          "1","2","3.4"
          "a","b","c"

          Note:

          • In Unix/Linux system, each line ends with "", namely "\n";
          • In Windows system, each line ends with ""
          • In Mac system, each line ends with "", namely "\n” and only Mac OS before v9 uses '\r'.
          • According to the file contents, set appropriate recordDelimiter.

          Select JSON file

          Please refer to the following codes for Java SDK to select JSON file:

          final String jsonContent = "{\n" +
                  "\t\"name\": \"Smith\",\n" +
                  "\t\"age\": 16,\n" +
                  "\t\"org\": null\n" +
                  "}\n" +
                  "{\n" +
                  "\t\"name\": \"charles\",\n" +
                  "\t\"age\": 27,\n" +
                  "\t\"org\": \"baidu\"\n" +
                  "}\n" +
                  "{\n" +
                  "\t\"name\": \"jack\",\n" +
                  "\t\"age\": 35,\n" +
                  "\t\"org\": \"bos\"\n" +
                  "}";
          client.putObject("bucketName", "test-json", new ByteArrayInputStream(jsonContent.getBytes()));
          SelectObjectRequest request = new SelectObjectRequest("bucketName", "test-json")
                  .withSelectType("json")
                  .withExpression("select * from BosObject where age > 20")
                  .withInputSerialization(new InputSerialization()
                          .withCompressionType("NONE")
                          .withJsonType("LINES"))
                  .withOutputSerialization(new OutputSerialization()
                          .withRecordDelimiter("\n"))
                  .withRequestProgress(false);
          SelectObjectResponse response = client.selectObject(request);
          // Output the returned records 
          SelectObjectResponse.Messages messages = response.getMessages();
          while (messages.hasNext()) {
              SelectObjectResponse.CommonMessage message = messages.next();
              if (message.Type.equals("Records")) {
                  for (String record: message.getRecords()) {
                      System.out.println(record);
                  }
              }
          }

          Select the results output by JSON file:

          {"name":"charles","age":27,"org":"baidu"}
          {"name":"jack","age":35,"org":"bos"}

          Note that the parameters to initialize SelectObjectRequest are very different for the query of CSV and JSON files. Please refer to SelectObject Interface for detailed parameter settings .

          Previous
          Bucket Management
          Next
          Data Processing and Use