最近更新时间:2022-07-25
本节介绍如何快速使用UOS Java SDK完成常见操作,如创建存储空间、上传文件、下载文件等。
桶相当于数据的容器,可以存储若干文件。 以下代码用于新建一个桶:
public void testCreateBucket() { Bucket b = null; if (s3.doesBucketExistV2(bucketName)) { System.out.format("Bucket %s already exists.\n", bucketName); } else { try { s3.createBucket(bucketName); } catch (AmazonS3Exception e) { System.err.println(e.getErrorMessage()); } } System.out.println("Done!"); } |
以下代码用于上传文件至UOS:
public void testPutObject() { try { File file = new File("s3Demo/src/L.jpeg"); PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file).withCannedAcl(CannedAccessControlList.PublicRead); s3.putObject(putObjectRequest); } catch (AmazonServiceException e) { System.err.println(e.getErrorMessage()); System.exit(1); } System.out.println("Done!"); } |
以下代码用于获取文件的文本内容:
public void testGetObject() { try { S3Object o = s3.getObject(bucketName, objectName); System.out.println(o); S3ObjectInputStream s3is = o.getObjectContent(); FileOutputStream fos = new FileOutputStream(new File("s3Demo/src/L.jpeg")); byte[] read_buf = new byte[1024]; int read_len = 0; while ((read_len = s3is.read(read_buf)) > 0) { fos.write(read_buf, 0, read_len); } s3is.close(); fos.close(); } catch (AmazonServiceException e) { System.err.println(e.getErrorMessage()); System.exit(1); }catch (FileNotFoundException e) { System.err.println(e.getMessage()); System.exit(1); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println("Done!"); } |
以下代码用于列举指定存储空间下的文件。
public void testListObjects() { try{ ListObjectsV2Result result = s3.listObjectsV2(bucketName); List objects = result.getObjectSummaries(); for (S3ObjectSummary os: objects) { System.out.println("* " + os.getKey()); } }catch (AmazonServiceException e) { System.err.println(e.getErrorMessage()); System.exit(1); } System.out.println("Done!"); } |
以下代码用于删除指定文件:
public void testDeleteObject(String bucketName,String objectName) { try{ s3.deleteObject(new DeleteObjectRequest(bucketName, objectName)); }catch (AmazonServiceException e) { System.err.println(e.getErrorMessage()); System.exit(1); } System.out.println("Done!"); } |