public static String endpoint = "oss-cn-chengdu.aliyuncs.com"; //地域节点 public static String keyid = ""; //accessKeyId public static String keysecret = ""; //accessKeySecret public static String bucketname = ""; //仓库名称
1、上传文件
/** * * @param content 文件内容 * @param objectName 文件名称 */ public static void upload(String content,String objectName){ OSS ossClient = new OSSClientBuilder().build(endpoint, keyid, keysecret); ossClient.putObject(bucketname,objectName,new ByteArrayInputStream(content.getBytes())); ossClient.shutdown(); }
2、读取文件内容
/** * * @param objectName 文件名称 * @return */ public static String downLoad(String objectName){ OSS ossClient = new OSSClientBuilder().build(endpoint, keyid, keysecret); OSSObject ossObject = ossClient.getObject(bucketname, objectName); BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent())); StringBuilder sb = new StringBuilder(); try { while (true) { String line = reader.readLine(); if (line == null) { break; } sb.append(line).append("\n"); } reader.close(); } catch (IOException e) { e.printStackTrace(); } // 关闭OSSClient。 ossClient.shutdown(); return sb.toString(); }
3、判断文件是否存在
/** * 判断文件是否存在 * * * @return true文件存在,false文件不存在 */ public static boolean isExitByFileName(String objectName) { OSS ossClient = new OSSClientBuilder().build(endpoint, keyid, keysecret); return ossClient.doesObjectExist(bucketname, objectName); }
4、删除文件
public static void delete(String objectName) { OSS ossClient = new OSSClientBuilder().build(endpoint, keyid, keysecret); ossClient.deleteObject(bucketname, objectName); }