阿里云OSS追加上传(java)

场景描述:不断接收数据,将数据写入文件存放到OSS

方案:

1、接收到文件后写到本地,定期或实时覆盖上传到OSS

2、OSS追加上传

只贴2代码:



public boolean writeFile(String content) {

		// 创建OSSClient实例

		OSSClient ossClient = new OSSClient(ossConfig.getEndPoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());



		try {

			// 判断bucket是否存在

			if (!ossClient.doesBucketExist(ossConfig.getBucketName())) {

				ossClient.createBucket(ossConfig.getBucketName());// 创建Bucket

				logger.info("Bucket {} 不存在,已创建。", ossConfig.getBucketName());

			}



			// 判断当日目录是否存在

			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

			Date today = new Date();

			String todayDirectoryName = ossConfig.getDirectory() + simpleDateFormat.format(today) + "/";

			if (!ossClient.doesObjectExist(ossConfig.getBucketName(), todayDirectoryName)) {

				OSSUtil.createDirectory(ossClient, ossConfig.getBucketName(), todayDirectoryName);

				logger.info("目录 {} 不存在,已创建。", todayDirectoryName);

			}



			InputStream inputStream = new ByteArrayInputStream(content.getBytes());



			// 按规则生成文件名

			String deviceFileName = todayDirectoryName + 文件名 + ".txt";



			// 从OSS取文件,读其大小

			Long position = OSSUtil.getRemoteFileSize(ossClient, ossConfig.getBucketName(), deviceFileName);

			logger.debug("{} 写入位置 {}", deviceFileName, position);



			// 创建上传Object的Metadata,如不声明则写入OSS中文会乱码

			ObjectMetadata meta = new ObjectMetadata();

			meta.setContentType("text/plain; charset=utf-8");



			ossClient.appendObject(new AppendObjectRequest(ossConfig.getBucketName(), deviceFileName, inputStream, meta).withPosition(position));



			return true;

		} catch (Exception e) {

			logger.error("OSS文件写入异常", e);

			return false;

		} finally {

			ossClient.shutdown();

		}

	}

~~~~

上一篇:重塑云上的 Java 语言


下一篇:分享工作中遇到的问题积累经验 事务日志太大导致insert不进数据