详细说明及api请参考官网,这里只整理常用的一些简单方法
ftpUtil
package platform.modules.claim.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.SocketException; import java.util.Arrays; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.alibaba.fastjson.JSON; @Component public final class FTPUtil { private final static Log logger = LogFactory.getLog(FTPUtil.class); // ftp主机地址 @Value("${ftpHost}") private String ftpHost; // ftp用户名 @Value("${ftpUserName}") private String ftpUserName; // ftp密码 @Value("${ftpPassword}") private String ftpPassword; // ftp端口 @Value("${ftpPort}") private int ftpPort; // ftp影像件地址 @Value("${ftpImagePath}") private String ftpImagePath; // ftp数据下载地址 @Value("${ftpDownPath}") private String ftpDownPath; // 本地临时存储文件夹 @Value("${localTempPath}") private String localTempPath; // 代理服务器 @Value("${proxyHost}") private String proxyHost; // 代理服务器端口 @Value("${proxyPort}") private int proxyPort; @Value("${proxyFlag}") private boolean proxyFlag; // ftp客户端 public FTPClient ftpClient; public FTPUtil(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String ftpImagePath, String ftpDownPath) { super(); this.ftpHost = ftpHost; this.ftpUserName = ftpUserName; this.ftpPassword = ftpPassword; this.ftpPort = ftpPort; this.ftpImagePath = ftpImagePath; this.ftpDownPath = ftpDownPath; } /** * 获取FTPClient对象 * * @param ftpHost FTP主机服务器 * @param ftpPassword FTP 登录密码 * @param ftpUserName FTP登录用户名 * @param ftpPort FTP端口 默认为21 * @return */ public FTPClient initClient() { ftpClient = new FTPClient(); try { if (proxyFlag) {// 使用代理模式 Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); ftpClient.setProxy(proxy); } ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器 boolean flag = ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器 // ftpClient.setKeepAlive(true); logger.info(flag + "登录标记:"); logger.info(JSON.toJSONString(ftpClient.getReplyCode())); if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { logger.error("未连接到FTP,用户名或密码错误。"); ftpClient.disconnect(); } else { logger.info("FTP连接成功。"); logger.info(JSON.toJSONString(ftpClient.listNames())); } } catch (SocketException e) { e.printStackTrace(); logger.error(e.getMessage()); logger.error("FTP的IP地址可能错误,请正确配置。"); } catch (IOException e) { e.printStackTrace(); logger.error(e.getMessage()); logger.error("FTP的端口错误,请正确配置。"); } return ftpClient; } /** * 列举文件列表 * * @param ftpPath ftp文件存放物理路径 */ public List<String> listFiles(String filePath) { initClient(); String[] fileNames = null; try { fileNames = ftpClient.listNames(filePath); } catch (IOException e) { e.printStackTrace(); } if (fileNames == null || fileNames.length <= 0) { logger.error("此文件夹下无文件"); return null; } return Arrays.asList(fileNames); } /** * 下载文件 * * @param ftpHost ftp服务器地址 * @param ftpUserName anonymous匿名用户登录,不需要密码。administrator指定用户登录 * @param ftpPassword 指定用户密码 * @param ftpPort ftp服务员器端口号 * @param ftpPath ftp文件存放物理路径 * @param fileName 文件路径 filepath ftp上文件路径 * @param input 文件输入流,即从本地服务器读取文件的IO输入流 */ public File downloadFile(String fileName, String filePath) { File localFile = null; OutputStream os = null; try { initClient(); ftpClient.setControlEncoding("UTF-8"); // 中文支持 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ftpClient.changeWorkingDirectory(filePath); String tempfilePath = localTempPath; localFile = new File(tempfilePath + fileName); os = new FileOutputStream(localFile); ftpClient.retrieveFile(fileName, os); } catch (FileNotFoundException e) { logger.error("没有找到" + filePath + fileName + "文件"); e.printStackTrace(); return null; } catch (SocketException e) { logger.error("连接FTP失败."); // e.printStackTrace(); return null; } catch (IOException e) { logger.error("文件读取错误。"); // e.printStackTrace(); return null; } finally { try { if (os != null) { os.close(); } ftpClient.logout(); //ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } logger.info("文件下载成功!" + filePath + fileName); return localFile; } /** * 下载文件 * * @param ftpHost ftp服务器地址 * @param ftpUserName anonymous匿名用户登录,不需要密码。administrator指定用户登录 * @param ftpPassword 指定用户密码 * @param ftpPort ftp服务员器端口号 * @param ftpPath ftp文件存放物理路径 * @param fileName 文件路径 * @param input 文件输入流,即从本地服务器读取文件的IO输入流 */ public File downloadFile(String fileName) { File localFile = null; try { initClient(); ftpClient.setControlEncoding("UTF-8"); // 中文支持 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ftpClient.changeWorkingDirectory(ftpImagePath); localFile = new File(localTempPath + File.separatorChar + fileName); OutputStream os = new FileOutputStream(localFile); ftpClient.retrieveFile(fileName, os); os.close(); ftpClient.logout(); } catch (FileNotFoundException e) { logger.error("没有找到" + ftpDownPath + "文件"); e.printStackTrace(); } catch (SocketException e) { logger.error("连接FTP失败."); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); logger.error("文件读取错误。"); e.printStackTrace(); } return localFile; } /** * 上传文件 * * @param ftpHost ftp服务器地址 * @param ftpUserName anonymous匿名用户登录,不需要密码。administrator指定用户登录 * @param ftpPassword 指定用户密码 * @param ftpPort ftp服务员器端口号 * @param ftpPath ftp文件存放物理路径 * @param fileName 文件名 * @param input 文件输入流,即从本地服务器读取文件的IO输入流 */ public boolean uploadFile(File zipFile) { if (!zipFile.exists()) { logger.error("文件不存在!"); return false; } InputStream input = null; String uploadFileName = zipFile.getName(); try { input = new FileInputStream(zipFile); ftpClient = initClient(); ftpClient.changeWorkingDirectory(ftpImagePath); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ftpClient.storeFile(uploadFileName, input); } catch (Exception e) { e.printStackTrace(); } finally { try { input.close(); ftpClient.logout(); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } return true; } /** * 上传文件 * * @param ftpHost ftp服务器地址 * @param ftpUserName anonymous匿名用户登录,不需要密码。administrator指定用户登录 * @param ftpPassword 指定用户密码 * @param ftpPort ftp服务员器端口号 * @param ftpPath ftp文件存放物理路径 * @param fileName 文件名 * @param input 文件输入流,即从本地服务器读取文件的IO输入流 */ public boolean uploadFile(File file, String uploadPath) { if (!file.exists()) { logger.error("文件不存在!"); return false; } InputStream input = null; String uploadFileName = file.getName(); try { input = new FileInputStream(file); ftpClient = initClient(); ftpClient.changeWorkingDirectory(uploadPath); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); uploadFileName = new String(uploadFileName.getBytes(), "UTF-8"); ftpClient.storeFile(uploadFileName, input); logger.info("upload成功!"); } catch (Exception e) { e.printStackTrace(); } finally { try { input.close(); ftpClient.logout(); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } return true; } /** * 上传文件 * * @param ftpHost ftp服务器地址 * @param ftpUserName anonymous匿名用户登录,不需要密码。administrator指定用户登录 * @param ftpPassword 指定用户密码 * @param ftpPort ftp服务员器端口号 * @param ftpPath ftp文件存放物理路径 * @param fileName 文件名 * @param input 文件输入流,即从本地服务器读取文件的IO输入流 */ public String[] ListFileNames(String uploadPath) { ftpClient = initClient(); try { return ftpClient.listNames(uploadPath); } catch (Exception e) { e.printStackTrace(); } finally { try { ftpClient.logout(); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } return null; } }
qCloudUtil
package platform.modules.claim.util; import java.io.*; import com.qcloud.cos.COSClient; import com.qcloud.cos.ClientConfig; import com.qcloud.cos.auth.BasicCOSCredentials; import com.qcloud.cos.auth.COSCredentials; import com.qcloud.cos.http.HttpProtocol; import com.qcloud.cos.model.COSObject; import com.qcloud.cos.model.COSObjectInputStream; import com.qcloud.cos.model.COSObjectSummary; import com.qcloud.cos.model.GetObjectRequest; import com.qcloud.cos.model.ListObjectsRequest; import com.qcloud.cos.model.ObjectListing; import com.qcloud.cos.model.ObjectMetadata; import com.qcloud.cos.model.PutObjectRequest; import com.qcloud.cos.model.PutObjectResult; import com.qcloud.cos.region.Region; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public final class QCloudCOSUtil { private static final Logger logger = LoggerFactory.getLogger(QCloudCOSUtil.class); // 申明变量 private String QCloudSecretId; private String QCloudSecretKey; private String bucketName; private String qcloudRegion; private COSCredentials cred; public COSClient cosClient; // 代理服务器 @Value("${proxyHost}") private String proxyHost; // 代理服务器端口 @Value("${proxyPort}") private int proxyPort; @Value("${proxyFlag}") private boolean proxyFlag; /** * 带参数构造 * @param qCloudSecretId * @param qCloudSecretKey * @param bucketName * @param qcloudRegion */ public QCloudCOSUtil(String qCloudSecretId, String qCloudSecretKey, String bucketName, String qcloudRegion) { super(); QCloudSecretId = qCloudSecretId; QCloudSecretKey = qCloudSecretKey; this.bucketName = bucketName; this.qcloudRegion = qcloudRegion; } /** * 初始化 */ public void init() { //// 1 初始化用户身份信息(secretId, secretKey) cred = new BasicCOSCredentials(QCloudSecretId, QCloudSecretKey); // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224 // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。 Region region = new Region(qcloudRegion); ClientConfig clientConfig = new ClientConfig(region); clientConfig.setHttpProtocol(HttpProtocol.https); if (proxyFlag) {// 使用代理模式 clientConfig.setHttpProxyIp(proxyHost); clientConfig.setHttpProxyPort(proxyPort); } // 3 生成 cos 客户端。 cosClient = new COSClient(cred, clientConfig); } /** * 关闭客户端 */ public void close() { // 关闭客户端(关闭后台线程) cosClient.shutdown(); } /** * 查看bucket下所有的object * @param bucketName 存储桶 */ public void getAllBucketObject(String prefixPath) { init(); try { ListObjectsRequest listObjectsRequest = new ListObjectsRequest(); // 设置 bucket 名称 listObjectsRequest.setBucketName(bucketName); // prefix 表示列出的 object 的 key 以 prefix 开始 listObjectsRequest.setPrefix(prefixPath); // 设置最大遍历出多少个对象, 一次 listobject 最大支持1000 listObjectsRequest.setMaxKeys(1000); // deliter表示分隔符, 设置为/表示列出当前目录下的object, 设置为空表示列出所有的object listObjectsRequest.setDelimiter(""); ObjectListing objectListing = cosClient.listObjects(listObjectsRequest); // common prefix表示表示被delimiter截断的路径, 如delimter设置为/, common prefix则表示所有子目录的路径 for (COSObjectSummary cosObjectSummary : objectListing.getObjectSummaries()) { // 对象的路径 key String key = cosObjectSummary.getKey(); // 对象的 etag String etag = cosObjectSummary.getETag(); // 对象的长度 long fileSize = cosObjectSummary.getSize(); // 对象的存储类型 String storageClass = cosObjectSummary.getStorageClass(); System.out.println("filekey:" + key + "; etag:" + etag + "; fileSize:" + fileSize + "; storageClass:" + storageClass+";"+cosObjectSummary.getBucketName()); } } catch (Exception exception) { exception.printStackTrace(); } finally { close(); } } /** * qcloud文件上传 * * @param cosClient * @param bucketName 保存到某个存储桶 * @param key 保存文件的key (以key-value形式保存)其实就是一个url路径 * @param file 上传文件 */ public PutObjectResult qcloudUpload(File localFile, String fileKey) { init(); PutObjectResult putObjectResult = null; try { PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileKey, localFile); putObjectResult = cosClient.putObject(putObjectRequest); } catch (Exception serverException) { serverException.printStackTrace(); } finally { close(); } return putObjectResult; } /** * qcloud文件上传 * 以文件流上传 * @param cosClient * @param bucketName 保存到某个存储桶 * @param key 保存文件的key (以key-value形式保存)其实就是一个url路径 * @param file 上传文件 */ public PutObjectResult qcloudUploadInput(File localFile, String fileKey) { init(); PutObjectResult putObjectResult = null; FileInputStream fileInputStream = null; try { // 方法2 从输入流上传(需提前告知输入流的长度, 否则可能导致 oom) fileInputStream = new FileInputStream(localFile); ObjectMetadata objectMetadata = new ObjectMetadata(); // 设置输入流长度为500 objectMetadata.setContentLength(500); // 设置 Content type, 默认是 application/octet-stream //content-type, 对于本地文件上传, 默认根据本地文件的后缀进行映射,如 jpg 文件映射 为image/jpg,可以不设置 objectMetadata.setContentType("image/jpg"); putObjectResult = cosClient.putObject(bucketName, fileKey, fileInputStream, objectMetadata); // 关闭输入流... } catch (Exception serverException) { serverException.printStackTrace(); } finally { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } close(); } return putObjectResult; } /** * qcloud文件上传 * 以文件流上传 * @param cosClient * @param bucketName 保存到某个存储桶 * @param key 保存文件的key (以key-value形式保存)其实就是一个url路径 * @param file 上传文件 */ public PutObjectResult qcloudUploadInput(InputStream fileInputStream, String fileKey) { init(); PutObjectResult putObjectResult = null; try { // 方法2 从输入流上传(需提前告知输入流的长度, 否则可能导致 oom) ObjectMetadata objectMetadata = new ObjectMetadata(); // 设置输入流长度为20971520 //objectMetadata.setContentLength(20971520); // 设置 Content type, 默认是 application/octet-stream //content-type, 对于本地文件上传, 默认根据本地文件的后缀进行映射,如 jpg 文件映射 为image/jpg,可以不设置 objectMetadata.setContentType("image/jpg"); putObjectResult = cosClient.putObject(bucketName, fileKey, fileInputStream, objectMetadata); // 关闭输入流... } catch (Exception serverException) { serverException.printStackTrace(); } finally { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } close(); } return putObjectResult; } /** * qcloud文件下载 * * @param bucketName 下载某个存储桶的数据 * @param key 下载文件的key * @param targetFilePath 下载文件保存地址 */ public ObjectMetadata qcloudDownload(String keyname, String targetFilePath) { init(); ObjectMetadata downObjectMeta = null; try { // 指定要下载到的本地路径 File downFile = new File(targetFilePath); GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, keyname); downObjectMeta = cosClient.getObject(getObjectRequest, downFile); } catch (Exception exception) { exception.printStackTrace(); } finally { close(); } return downObjectMeta; } /** * qcloud文件下载,获取对象流 * * @param bucketName 下载某个存储桶的数据 * @param key 下载文件的key */ public COSObjectInputStream qcloudDownloadInput(String keyname) { init(); COSObjectInputStream cosObjectInput = null; try { // 指定要下载到的本地路径 GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, keyname); COSObject cosObject = cosClient.getObject(getObjectRequest); cosObjectInput = cosObject.getObjectContent(); } catch (Exception exception) { exception.printStackTrace(); logger.error("文件不存在"); return null; } finally { close(); } return cosObjectInput; } /** * 文件删除 * * @param cosClient * @param bucketName 删除文件所在存储桶 * @param key 删除文件key */ public void qcloudDeleteObject(String bucketName, String key) { init(); try { cosClient.deleteObject(bucketName, key); } catch (Exception exception) { exception.printStackTrace(); } finally { close(); } } }