---
title: "从零开始，在java中使用七牛云实现文件云存储（三）"
author: "Du_wood"
date: "2017-12-24T19:51:37Z"
tags: []
categories: ["互联网"]
slug: "java"
draft: false
lastmod: "2017-12-24T19:51:37Z"
id: 2405600
url: "https://dushen.iteye.com/blog/2405600"
---

在上一篇博客中，笔者简单介绍了qiniu SDK的资源管理以及各种上传凭证的生成，本章笔者将介绍qiniu SDK的资源批量管理功能。

 

上篇文章的链接：[从零开始，在java中使用七牛云实现文件云存储（二）](/blog/2405023 "从零开始，在java中使用七牛云实现文件存储（二）")

 

进入正题！

1. 批量获取文件状态：
   
   ```
   /**
   	 * 批量获取文件状态
   	 * @param zone
   	 * @param auth
   	 * @param keyList 文件名列表， 单次批量请求的文件数量不得超过1000
   	 * @param bucket
   	 * @return
   	 */
   	public static BatchStatus[] getFilesStat(Zone zone,Auth auth,String[] keyList,String bucket) {
   		// 构造一个带指定Zone对象的配置类
   		Configuration cfg = new Configuration(zone);
   		BucketManager bucketManager = new BucketManager(auth, cfg);
   		try {
   			BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
   			batchOperations.addStatOps(bucket, keyList);
   			Response response = bucketManager.batch(batchOperations);
   			BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
   			for (int i = 0; i < keyList.length; i++) {
   				BatchStatus status = batchStatusList[i];
   				String key = keyList[i];
   				System.out.print(key + "\t");
   				if (status.code == 200) {
   					// 文件存在
   					System.out.println(status.data.hash);
   					System.out.println(status.data.mimeType);
   					System.out.println(status.data.fsize);
   					System.out.println(status.data.putTime);
   				} else {
   					System.out.println(status.data.error);
   				}
   			}
   			return batchStatusList;
   		} catch (QiniuException ex) {
   			System.err.println(ex.response.toString());
   		}
   		return null;
   	}
   ```
   
    说明：参数keyList：想要获取状态的文件名数组。
2. 批量修改文件类型：
   
   ```
   /**
   	 * 批量修改文件类型，单次批量请求的文件数量不得超过1000
   	 * @param zone
   	 * @param auth
   	 * @param keyMimeMap  文件名：目的类型 ，例keyMimeMap.put("qiniu.jpg", "image/jpg");
   	 * @param bucket
   	 * @return
   	 */
   	public static BatchStatus[] editFilesType(Zone zone,Auth auth,HashMap<String, String> keyMimeMap,String bucket) {
   		//构造一个带指定Zone对象的配置类
   		Configuration cfg = new Configuration(zone);
   		BucketManager bucketManager = new BucketManager(auth, cfg);
   		try {
   		    BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
   		    //添加指令
   		    for (Map.Entry<String, String> entry : keyMimeMap.entrySet()) {
   		        String key = entry.getKey();
   		        String newMimeType = entry.getValue();
   		        batchOperations.addChgmOp(bucket, key, newMimeType);
   		    }
   		    Response response = bucketManager.batch(batchOperations);
   		    BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
   		    int index = 0;
   		    for (Map.Entry<String, String> entry : keyMimeMap.entrySet()) {
   		        String key = entry.getKey();
   		        System.out.print(key + "\t");
   		        BatchStatus status = batchStatusList[index];
   		        if (status.code == 200) {
   		            System.out.println("change mime success");
   		        } else {
   		            System.out.println(status.data.error);
   		        }
   		        index += 1;
   		    }
   		    return batchStatusList;
   		} catch (QiniuException ex) {
   		    System.err.println(ex.response.toString());
   		}
   		return null;
   	}
   ```
   
    说明：参数keyMimeMap：map型参数，key为待处理文件名，value为想要修改成的文件格式。
3. 批量删除：
   
   ```
   /**
   	 * 批量删除文件
   	 * @param zone
   	 * @param auth
   	 * @param keyList 文件名列表， 单次批量请求的文件数量不得超过1000
   	 * @param bucket
   	 * @return
   	 */
   	public static BatchStatus[] deleteFiles(Zone zone,Auth auth,String[] keyList,String bucket) {
   		//构造一个带指定Zone对象的配置类
   		Configuration cfg = new Configuration(zone);
   		BucketManager bucketManager = new BucketManager(auth, cfg);
   		try {
   		    //单次批量请求的文件数量不得超过1000
   		    BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
   		    batchOperations.addDeleteOp(bucket, keyList);
   		    Response response = bucketManager.batch(batchOperations);
   		    BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
   		    for (int i = 0; i < keyList.length; i++) {
   		        BatchStatus status = batchStatusList[i];
   		        String key = keyList[i];
   		        System.out.print(key + "\t");
   		        if (status.code == 200) {
   		            System.out.println("delete success");
   		        } else {
   		            System.out.println(status.data.error);
   		        }
   		    }
   		    return batchStatusList;
   		} catch (QiniuException ex) {
   		    System.err.println(ex.response.toString());
   		    return null;
   		}
   	}
   ```
   
    说明：参数keyList：想要获取状态的文件名数组。
4. 批量移动：
   
   ```
   /**
   	 * 批量移动文件，可用作重命名
   	 * @param zone
   	 * @param auth
   	 * @param opts 操作集合
   	 * @return
   	 */
   	public static BatchStatus[] moveOrRenameFiles(Zone zone,Auth auth,List<OptInfo> opts) {
   		//构造一个带指定Zone对象的配置类
   		Configuration cfg = new Configuration(zone);
   		BucketManager bucketManager = new BucketManager(auth, cfg);
   		try {
   		    //单次批量请求的文件数量不得超过1000
   		    BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
   		    for (OptInfo opt : opts) {
   		        batchOperations.addMoveOp(opt.getFromBucket(), opt.getFromKey(), opt.getToBucket(), opt.getToKey());
   		    }
   		    Response response = bucketManager.batch(batchOperations);
   		    BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
   		    for (int i = 0; i < opts.size(); i++) {
   		        BatchStatus status = batchStatusList[i];
   		        String key = opts.get(i).getFromKey();
   		        System.out.print(key + "\t");
   		        if (status.code == 200) {
   		            System.out.println("move success");
   		        } else {
   		            System.out.println(status.data.error);
   		        }
   		    }
   		    return batchStatusList;
   		} catch (QiniuException ex) {
   		    System.err.println(ex.response.toString());
   		}
   		return null;
   	}
   ```
   
    说明：参数opts：封装了源和目的文件名和空间名，代码如下：
   
   ```
   public class OptInfo {
   	private String fromBucket;
   	private String fromKey;
   	private String toBucket;
   	private String toKey;
   	
   	public OptInfo(String fromBucket, String fromKey, String toBucket, String toKey) {
   		super();
   		this.fromBucket = fromBucket;
   		this.fromKey = fromKey;
   		this.toBucket = toBucket;
   		this.toKey = toKey;
   	}
   	//
   	//节省篇幅getters and setters不粘了
   }
   ```
5. 批量复制：
   
   ```
   /**
   	 * 批量复制
   	 * @param zone
   	 * @param auth
   	 * @param opts 操作集合
   	 * @return
   	 */
   	public static BatchStatus[] copyFiles(Zone zone,Auth auth,List<OptInfo> opts) {
   		//构造一个带指定Zone对象的配置类
   		Configuration cfg = new Configuration(zone);
   		BucketManager bucketManager = new BucketManager(auth, cfg);
   		try {
   		    BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
   		    for (OptInfo opt : opts) {
   		        batchOperations.addCopyOp(opt.getFromBucket(), opt.getFromKey(), opt.getToBucket(), opt.getToKey());
   		    }
   		    Response response = bucketManager.batch(batchOperations);
   		    BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
   		    for (int i = 0; i < opts.size(); i++) {
   		        BatchStatus status = batchStatusList[i];
   		        String key = opts.get(i).getFromKey();
   		        System.out.print(key + "\t");
   		        if (status.code == 200) {
   		            System.out.println("copy success");
   		        } else {
   		            System.out.println(status.data.error);
   		        }
   		    }
   		    return batchStatusList;
   		} catch (QiniuException ex) {
   		    System.err.println(ex.response.toString());
   		}
   		return null;
   	}
   ```
   
    说明：参数opts同上。
6. 批量混合操作：
   
   ```
   	/**
   	 * 混合批量操作，单次批量请求的文件数量不得超过1000
   	 * @param zone
   	 * @param auth
   	 * @param batchOperations 批量指令集
   	 * 		例batchOperations.addStatOps(bucket, "qiniu.png", "qiniu.jpg");
   	 *		  batchOperations.addCopyOp(bucket, "qiniu.png", bucket, "qiniu_copy1.png");
   	 *		  batchOperations.addMoveOp(bucket, "qiniu2.png", bucket, "qiniu3.png");
   	 *		  batchOperations.addDeleteOp(bucket, "qiniu4.png");
   	 * @return
   	 */
   	public static BatchStatus[] fixOpts(Zone zone,Auth auth,BucketManager.BatchOperations batchOperations) {
   		//构造一个带指定Zone对象的配置类
   		Configuration cfg = new Configuration(zone);
   		BucketManager bucketManager = new BucketManager(auth, cfg);
   		try {
   		    Response response = bucketManager.batch(batchOperations);
   		    BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
   		    for (BatchStatus status : batchStatusList) {
   		        if (status.code == 200) {
   		            System.out.println("operation success");
   		        } else {
   		            System.out.println(status.data.error);
   		        }
   		    }
   		    return batchStatusList;
   		} catch (QiniuException ex) {
   		    System.err.println(ex.response.toString());
   		}
   		return null;
   	}
   ```
   
    说明：参数batchOperations：批量指令集，可以删除、移动等指令，具体用法请看代码注释。

对上几个方法统一实验一下：

```
	public static void main(String[] args) {
		Zone zone=Zone.zone0();
		Auth auth=CredentialsManager.getAuth();
		String bucket="你的空间名";
		
//		//测试getFilesStat
//		getFilesStat(zone, auth, new String[]{"2.jpg","3.jpg","4.jpg","noFile.jpg"},bucket);
//		
//		//测试editFilesType
//		HashMap<String,String> keyMimeMap =new HashMap<>();
//		keyMimeMap. put("2.jpg", "text/plain");
//		keyMimeMap. put("4.jpg", "text/plain");
//		editFilesType(zone, auth, keyMimeMap, bucket);
//		
//		//测试deleteFiles
//		deleteFiles(zone, auth, new String[]{"5.jpg","3.jpg","noFile.jpg"}, bucket);
//		
//		//测试moveOrRenameFiles
//		List<OptInfo> opts=new ArrayList<>();
//		opts.add(new OptInfo(bucket, "as.txt", "bucket2", "as.txt"));
//		opts.add(new OptInfo(bucket, "sa.txt", "bucket2", "as.txt"));
//		moveOrRenameFiles(zone, auth, opts);
//		
//		//测试copyFiles
//		List<OptInfo> opts2=new ArrayList<>();
//		opts2.add(new OptInfo(bucket, "fff.txt", "bucket2", "fff.txt"));
//		opts2.add(new OptInfo(bucket, "ggg.txt", "bucket2", "ggg.txt"));
//		copyFiles(zone, auth, opts2);
//		
//		//测试fixOpts
//		BatchOperations batchOperations=new BatchOperations();
//		batchOperations.addDeleteOp(bucket, new String[]{"15.jpg","13.jpg","noFile.jpg"});
//		batchOperations.addCopyOp(bucket, "mmm.txt", "bucket2", "mmm.txt");
//		fixOpts(zone, auth, batchOperations);
}
```

 相关操作在前两篇博客已经说过了，在此不再多说。

 

 

好了，关于七牛云存储的介绍就写到这了！

七牛还提供了好多有意思的API，比如说音视频转码、图片鉴黄鉴暴、政治人物识别、水印、图片压缩等好多功能，如果你有需要或者感兴趣的话，请查看[官方文档](https://developer.qiniu.com/dora "官方文档")：https://developer.qiniu.com/dora