sftp,ftp文件下载
一、sftp工具类
- package com.ztesoft.iotcmp.util;
- import com.jcraft.jsch.ChannelSftp;
- import com.jcraft.jsch.JSch;
- import com.jcraft.jsch.JSchException;
- import com.jcraft.jsch.Session;
- import com.jcraft.jsch.SftpException;
- import java.io.*;
- import java.net.SocketException;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Properties;
- import java.util.Vector;
- import java.util.zip.GZIPInputStream;
- public class SftpUtil implements AutoCloseable {
- private Session session = null;
- private ChannelSftp channel = null;
- private String userName = "bi";
- private String passWord = "bi";
- private String hostName = "10.40.197.41";
- private String port = "";
- private String workDir = "test/download";
- public SftpUtil(String hostName, String port, String userName
- , String passWord, String workDir) throws IOException, JSchException {
- this.hostName = hostName;
- this.port = port;
- this.userName = userName;
- this.passWord = passWord;
- this.workDir = workDir;
- connectServer(hostName, Integer.parseInt(port), userName, passWord);
- }
- /**
- * 连接sftp服务器
- *
- * @param serverIP 服务IP
- * @param port 端口
- * @param userName 用户名
- * @param password 密码
- * @throws SocketException SocketException
- * @throws IOException IOException
- * @throws JSchException JSchException
- */
- public void connectServer(String serverIP, int port, String userName, String password) throws JSchException {
- JSch jsch = new JSch();
- // 根据用户名,主机ip,端口获取一个Session对象
- session = jsch.getSession(userName, serverIP, port);
- // 设置密码
- session.setPassword(password);
- // 为Session对象设置properties
- Properties config = new Properties();
- config.put("StrictHostKeyChecking", "no");
- session.setConfig(config);
- // 通过Session建立链接
- session.connect();
- // 打开SFTP通道
- channel = (ChannelSftp) session.openChannel("sftp");
- // 建立SFTP通道的连接
- channel.connect();
- }
- /**
- * 自动关闭资源
- */
- public void close() {
- if (channel != null) {
- channel.disconnect();
- }
- if (session != null) {
- session.disconnect();
- }
- }
- /**
- * @param path
- * @throws SftpException
- * @return获取目录下文件名称
- */
- public List<String> getDirFileList(String path) throws SftpException {
- List<String> list = new ArrayList<>();
- if (channel != null) {
- Vector vv = channel.ls(path);
- if (vv == null && vv.size() == 0) {
- return list;
- } else {
- Object[] aa = vv.toArray();
- for (int i = 0; i < aa.length; i++) {
- System.out.print(aa[i].toString());
- ChannelSftp.LsEntry temp = (ChannelSftp.LsEntry) aa[i];
- //获取文件名称
- String fileName = temp.getFilename();
- //判断文件名称是否为点
- if (!fileName.equals(".") && !fileName.equals("..")) {
- //判断文件是否为目录
- if (!temp.getAttrs().isDir()) {
- list.add(fileName);
- }
- }
- }
- }
- }
- return list;
- }
- /**
- * 下载文件
- *
- * @param remotePathFile 远程文件
- * @param localPathFile 本地文件[绝对路径]
- * @throws SftpException SftpException
- * @throws IOException IOException
- */
- public void downloadFile(String remotePathFile, String localPathFile) throws SftpException, IOException {
- try (FileOutputStream os = new FileOutputStream(new File(localPathFile))) {
- if (channel == null)
- throw new IOException("sftp server not login");
- channel.get(remotePathFile, os);
- }
- }
- /**
- * 下载文件
- *
- * @param downloadFile 下载的文件
- * @param saveFile 存在本地的路径
- */
- public void download(String downloadFile, String saveFile) throws SftpException, FileNotFoundException {
- if (workDir != null && !"".equals(workDir)) {
- channel.cd(workDir);
- }
- File file = new File(saveFile);
- channel.get(downloadFile, new FileOutputStream(file));
- System.out.println("下载文件到"+saveFile+"目录完成!");
- }
- /**
- * 下载文件
- *
- * @param downloadFile 下载的文件
- */
- public InputStream download(String downloadFile) {
- InputStream in = null;
- try {
- channel.cd(workDir);
- in = channel.get(downloadFile);
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException(e);
- }
- return in;
- }
- /**
- * 上传文件
- *
- * @param remoteFile 远程文件
- * @param localFile
- * @throws SftpException
- * @throws IOException
- */
- public void uploadFile(String remoteFile, String localFile) throws SftpException, IOException {
- try (FileInputStream in = new FileInputStream(new File(localFile))) {
- if (channel == null)
- throw new IOException("sftp server not login");
- channel.put(in, remoteFile);
- }
- }
- /**
- * 下载流文件
- *
- * @param remoteFileName
- * @return
- * @throws SftpException
- * @throws IOException
- */
- public BufferedReader downloadGZFile(String remoteFileName) throws SftpException, IOException {
- BufferedReader returnValue = null;
- //跳转目录
- Boolean state = openDir(this.workDir, channel);
- //判断是否跳转到指定目录
- if (state) {
- InputStream in = new GZIPInputStream(channel.get(remoteFileName));
- if (in != null) {
- returnValue = new BufferedReader(new InputStreamReader(in));
- System.out.println("<----------- INFO: download " + this.workDir + "/" + remoteFileName + " from ftp : succeed! ----------->");
- } else {
- System.out.println("<----------- ERR : download " + this.workDir + "/" + remoteFileName + " from ftp : failed! ----------->");
- }
- }
- return returnValue;
- }
- /**
- * 跳转到指定的目录
- *
- * @param directory
- * @param sftp
- * @return
- */
- public static boolean openDir(String directory, ChannelSftp sftp) {
- try {
- sftp.cd(directory);
- return true;
- } catch (SftpException e) {
- return false;
- }
- }
- public String getWorkDir() {
- return this.workDir;
- }
- }
二、文件处理思想流程
获取sftp连接
- SftpUtil sftpUtil = new SftpUtil(host,port,userName,passWord,dir);
根据路径获取文件列表
- List<String> fileList = sftpUtil.getDirFileList(sftpUtil.getWorkDir());
- if (fileList == null || fileList.isEmpty()) {
- throw new RuntimeException("没有文件要处理!");
- }
判断文件是否处理过
- boolean flag = SftpConfigUtil.checkFileIsDeal(fileName);//此处是根据表数据查询
未处理,进行处理过程
- if (!flag){
- BufferedReader reader = sftpUtil.downloadGZFile(fileName);//下载压缩文件并转化为流
- List<TempPaymentDayAuditFileDTO> dataList = paseReader(reader, fileName);//解析文件字段,注意关闭文件流reader.close();
- tempPaymentDayAuditService.insertPaymentDayAudits(dataList);//插入数据库
- SftpConfigUtil.insertFileIsDeal(fileName);//插入文件已处理标记到数据表中
- }
关闭sftp连接
- sftpUtil.close();
三、ftp工具类
- package com.ztesoft.iotcmp.util;
- import org.apache.commons.io.IOUtils;
- import org.apache.commons.net.ftp.FTP;
- import org.apache.commons.net.ftp.FTPClient;
- import org.apache.commons.net.ftp.FTPFile;
- import org.apache.commons.net.ftp.FTPReply;
- import java.io.*;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
- import java.util.zip.GZIPInputStream;
- /**
- * Ftp操作工具类
- *
- * @author easonwu
- *
- */
- public class FtpUtil {
- private String userName = "bi";
- private String passWord = "bi";
- private String hostName = "10.40.197.41" ;
- private String port = "" ;
- private String workDir = "test/download" ;
- private FTPClient ftpClient = new FTPClient();
- public FtpUtil() throws IOException {
- initailCheck() ;
- }
- public FtpUtil(String hostName , String port , String userName
- , String passWord , String workDir) throws IOException {
- this.hostName = hostName ;
- this.port = port ;
- this.userName = userName ;
- this.passWord = passWord ;
- this.workDir = workDir ;
- initailCheck() ;
- }
- private void initailCheck() throws IOException {
- connectToServer();
- if( this.workDir != null && !"".endsWith(this.workDir )){
- checkPathExist(this.workDir);
- }
- closeConnect();
- }
- /**
- * 查找指定目录是否存在
- * @param filePath 要查找的目录
- * @return boolean:存在:true,不存在:false
- * @throws IOException
- */
- private boolean checkPathExist(String filePath) throws IOException {
- boolean existFlag = false;
- try {
- if (!ftpClient.changeWorkingDirectory(filePath)) {
- ftpClient.makeDirectory(filePath);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return existFlag;
- }
- /**
- * 连接到ftp服务器
- */
- private void connectToServer() throws IOException{
- if(!ftpClient.isConnected()){
- int reply;
- try{
- ftpClient = new FTPClient();
- ftpClient.enterLocalPassiveMode();
- if(this.port == null || "".equals(this.port)){
- ftpClient.connect(this.hostName);
- }
- else{
- ftpClient.connect(this.hostName, Integer.parseInt(this.port));
- }
- ftpClient.login(userName, passWord);
- reply = ftpClient.getReplyCode();
- if(!FTPReply.isPositiveCompletion(reply)){
- ftpClient.disconnect();
- System.err.println("FTP server refused connection.");
- }
- }
- catch(IOException e){
- // System.err.println("登录ftp服务器【" + this.hostName + "】失败");
- e.printStackTrace();
- throw new IOException("登录ftp服务器【" + this.hostName + "】失败");
- }
- }
- }
- /**
- * 关闭连接
- */
- private void closeConnect() {
- try {
- if (ftpClient != null) {
- ftpClient.logout();
- ftpClient.disconnect();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 转码[GBK -> ISO-8859-1]
- * 不同的平台需要不同的转码
- * @param obj
- * @return
- */
- private static String gbkToIso8859(Object obj) {
- try {
- if (obj == null)
- return "";
- else
- return new String(obj.toString().getBytes("GBK"), "iso-8859-1");
- } catch (Exception e) {
- return "";
- }
- }
- /**
- * 转码[ISO-8859-1 -> GBK]
- * 不同的平台需要不同的转码
- * @param obj
- * @return
- */
- private static String iso8859ToGbk(Object obj) {
- try {
- if (obj == null)
- return "";
- else
- return new String(obj.toString().getBytes("iso-8859-1"), "GBK");
- } catch (Exception e) {
- return "";
- }
- }
- /**
- * 设置传输文件的类型[文本文件或者二进制文件]
- * @param fileType--BINARY_FILE_TYPE、ASCII_FILE_TYPE
- */
- private void setFileType(int fileType) {
- try {
- ftpClient.setFileType(fileType);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private void changeDir(String filePath) throws IOException {
- // 跳转到指定的文件目录
- if (filePath != null && !filePath.equals("")) {
- if (filePath.indexOf("/") != -1) {
- int index = 0;
- while ((index = filePath.indexOf("/")) != -1) {
- System.out.println("P:"+ filePath.substring(0,
- index)) ;
- ftpClient.changeWorkingDirectory(filePath.substring(0,
- index));
- filePath = filePath.substring(index + 1, filePath.length());
- }
- if (!filePath.equals("") && !"/".equals(filePath)) {
- ftpClient.changeWorkingDirectory(filePath);
- }
- } else {
- ftpClient.changeWorkingDirectory(filePath);
- }
- }
- }
- /**
- * check file
- * @param filePath
- * @param fileName
- * @return
- * @throws IOException
- */
- private boolean checkFileExist(String filePath, String fileName)
- throws IOException {
- boolean existFlag = false;
- changeDir( filePath ) ;
- String[] fileNames = ftpClient.listNames();
- if (fileNames != null && fileNames.length > 0) {
- for (int i = 0; i < fileNames.length; i++) {
- System.out.println("File:" + iso8859ToGbk(fileNames[i])) ;
- if (fileNames[i] != null
- && iso8859ToGbk(fileNames[i]).equals(fileName)) {
- existFlag = true;
- break;
- }
- }
- }
- ftpClient.changeToParentDirectory();
- return existFlag;
- }
- /**
- * download ftp file as inputstream
- * @param remoteFileName
- * @return
- * @throws IOException
- */
- public InputStream downloadFile(
- String remoteFileName) throws IOException {
- InputStream returnValue = null;
- //下载文件
- BufferedOutputStream buffOut = null;
- try {
- //连接ftp服务器
- connectToServer();
- if (!checkFileExist(this.workDir, remoteFileName)) {
- System.out.println("<----------- ERR : file " + this.workDir + "/" + remoteFileName+ " does not exist, download failed!----------->");
- return null;
- } else {
- changeDir( this.workDir ) ;
- String[] fileNames = ftpClient.listNames();
- //设置传输二进制文件
- setFileType(FTP.BINARY_FILE_TYPE);
- //获得服务器文件
- InputStream in = ftpClient.retrieveFileStream(remoteFileName);
- //输出操作结果信息
- if (in != null) {
- returnValue = new ByteArrayInputStream(IOUtils.toByteArray(in));
- in.close();
- System.out.println("<----------- INFO: download "+ this.workDir + "/" + remoteFileName+ " from ftp : succeed! ----------->");
- } else {
- System.out.println("<----------- ERR : download "+ this.workDir + "/" + remoteFileName+ " from ftp : failed! ----------->");
- }
- }
- //关闭连接
- closeConnect();
- } catch (Exception e) {
- e.printStackTrace();
- returnValue = null;
- //输出操作结果信息
- System.out.println("<----------- ERR : download " + this.workDir + "/" + remoteFileName+ " from ftp : failed! ----------->");
- } finally {
- try {
- if (ftpClient.isConnected()) {
- closeConnect();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return returnValue;
- }
- /**
- *
- * @param remoteFilePath
- * @param remoteFileName
- * @param localFileName
- * @return
- * @throws IOException
- */
- public boolean downloadFile(String remoteFilePath,
- String remoteFileName, String localFileName) throws IOException {
- boolean returnValue = false;
- //下载文件
- BufferedOutputStream buffOut = null;
- try {
- //连接ftp服务器
- connectToServer();
- File localFile = new File(localFileName.substring(0, localFileName
- .lastIndexOf("/")));
- if (!localFile.exists()) {
- localFile.mkdirs();
- }
- if (!checkFileExist(remoteFilePath, remoteFileName)) {
- System.out.println("<----------- ERR : file " + remoteFilePath + "/" + remoteFileName+ " does not exist, download failed!----------->");
- return false;
- } else {
- changeDir( remoteFilePath ) ;
- String[] fileNames = ftpClient.listNames();
- //设置传输二进制文件
- setFileType(FTP.BINARY_FILE_TYPE);
- //获得服务器文件
- buffOut = new BufferedOutputStream(new FileOutputStream(
- localFileName));
- returnValue = ftpClient.retrieveFile(
- remoteFileName, buffOut);
- //输出操作结果信息
- if (returnValue) {
- System.out.println("<----------- INFO: download "+ remoteFilePath + "/" + remoteFileName+ " from ftp : succeed! ----------->");
- } else {
- System.out.println("<----------- ERR : download "+ remoteFilePath + "/" + remoteFileName+ " from ftp : failed! ----------->");
- }
- }
- //关闭连接
- closeConnect();
- } catch (Exception e) {
- e.printStackTrace();
- returnValue = false;
- //输出操作结果信息
- System.out.println("<----------- ERR : download " + remoteFilePath+ "/" + remoteFileName+ " from ftp : failed! ----------->");
- } finally {
- try {
- if (buffOut != null) {
- buffOut.close();
- }
- if (ftpClient.isConnected()) {
- closeConnect();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return returnValue;
- }
- /**
- *
- * @param remoteFileNameList
- * @return
- * @throws IOException
- */
- public List batchDownloadFile(
- List remoteFileNameList) throws IOException {
- InputStream resultIs = null ;
- List inputStreamList = null ;
- String remoteFileName = null ;
- if( remoteFileNameList == null ||remoteFileNameList.isEmpty() ) return null ;
- inputStreamList = new ArrayList() ;
- for( Iterator it = remoteFileNameList.iterator() ; it.hasNext() ; ) {
- remoteFileName = (String)it.next() ;
- resultIs = this.downloadFile(remoteFileName);
- if (resultIs != null ) {
- inputStreamList.add(resultIs) ;
- }
- }
- return inputStreamList;
- }
- /**
- * 删除服务器上文件
- *
- * @param fileDir
- * 文件路径
- * @param fileName
- * 文件名称
- * @throws IOException
- */
- public boolean delFile(String fileDir, String fileName) throws IOException {
- boolean returnValue = false;
- try {
- //连接ftp服务器
- connectToServer();
- //跳转到指定的文件目录
- if (fileDir != null) {
- if (fileDir.indexOf("/") != -1) {
- int index = 0;
- while ((index = fileDir.indexOf("/")) != -1) {
- ftpClient.changeWorkingDirectory(fileDir.substring(0,
- index));
- fileDir = fileDir
- .substring(index + 1, fileDir.length());
- }
- if (!fileDir.equals("")) {
- ftpClient.changeWorkingDirectory(fileDir);
- }
- } else {
- ftpClient.changeWorkingDirectory(fileDir);
- }
- }
- //设置传输二进制文件
- setFileType(FTP.BINARY_FILE_TYPE);
- //获得服务器文件
- returnValue = ftpClient.deleteFile(fileName);
- //关闭连接
- closeConnect();
- //输出操作结果信息
- if (returnValue) {
- System.out.println("<----------- INFO: delete " + fileDir + "/"
- + fileName + " at ftp:succeed! ----------->");
- } else {
- System.out.println("<----------- ERR : delete " + fileDir + "/"
- + fileName + " at ftp:failed! ----------->");
- }
- } catch (Exception e) {
- e.printStackTrace();
- returnValue = false;
- //输出操作结果信息
- System.out.println("<----------- ERR : delete " + fileDir + "/"
- + fileName + " at ftp:failed! ----------->");
- } finally {
- try {
- if (ftpClient.isConnected()) {
- closeConnect();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return returnValue;
- }
- /**
- * upload file to ftp
- * @param uploadFile
- * @param fileName
- * @return
- * @throws IOException
- */
- public boolean uploadFile(String uploadFile , String fileName ) throws IOException{
- if(uploadFile == null || "".equals(uploadFile.trim())){
- System.out.println("<----------- ERR : uploadFile:" + uploadFile
- + " is null , upload failed! ----------->");
- return false ;
- }
- return this.uploadFile(new File(uploadFile) , fileName ) ;
- }
- /**
- * batch upload files
- * @param uploadFileList
- * @return
- * @throws IOException
- */
- public boolean batchUploadFile(List uploadFileList ) throws IOException{
- if(uploadFileList == null || uploadFileList.isEmpty()){
- System.out.println("<----------- ERR : batchUploadFile failed! because the file list is empty ! ----------->");
- return false ;
- }
- for( Iterator it = uploadFileList.iterator() ; it.hasNext() ;){
- File uploadFile = (File)it.next() ;
- if( !uploadFile(uploadFile , uploadFile.getName() ) ){
- System.out.println("<----------- ERR : upload file【"+uploadFile.getName()+"】 failed! ----------->") ;
- return false ;
- }
- }
- return true ;
- }
- /**
- * upload file to ftp
- * @param uploadFile
- * @param fileName
- * @return
- * @throws IOException
- */
- public boolean uploadFile(File uploadFile, String fileName)
- throws IOException {
- if (!uploadFile.exists()) {
- System.out.println("<----------- ERR : an named " + fileName
- + " not exist, upload failed! ----------->");
- return false;
- }
- return this.uploadFile(new FileInputStream(uploadFile) , fileName ) ;
- }
- /**
- * upload file to ftp
- * @param is
- * @param fileName
- * @return
- * @throws IOException
- */
- public boolean uploadFile(InputStream is , String fileName ) throws IOException {
- boolean returnValue = false;
- // 上传文件
- BufferedInputStream buffIn = null;
- try {
- // 建立连接
- connectToServer();
- // 设置传输二进制文件
- setFileType(FTP.BINARY_FILE_TYPE);
- // 获得文件
- buffIn = new BufferedInputStream(is);
- // 上传文件到ftp
- ftpClient.enterLocalPassiveMode();
- returnValue = ftpClient.storeFile(gbkToIso8859(this.workDir + "/"
- + fileName), buffIn);
- // 输出操作结果信息
- if (returnValue) {
- System.out.println("<----------- INFO: upload file to ftp : succeed! ----------->");
- } else {
- System.out.println("<----------- ERR : upload file to ftp : failed! ----------->");
- }
- // 关闭连接
- closeConnect();
- } catch (Exception e) {
- e.printStackTrace();
- returnValue = false;
- System.out.println("<----------- ERR : upload file to ftp : failed! ----------->");
- } finally {
- try {
- if (buffIn != null) {
- buffIn.close();
- }
- if (ftpClient.isConnected()) {
- closeConnect();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return returnValue ;
- }
- public boolean changeDirectory(String path) throws IOException {
- return ftpClient.changeWorkingDirectory(path);
- }
- public boolean createDirectory(String pathName) throws IOException {
- return ftpClient.makeDirectory(pathName);
- }
- public boolean removeDirectory(String path) throws IOException {
- return ftpClient.removeDirectory(path);
- }
- // delete all subDirectory and files.
- public boolean removeDirectory(String path, boolean isAll)
- throws IOException {
- if (!isAll) {
- return removeDirectory(path);
- }
- FTPFile[] ftpFileArr = ftpClient.listFiles(path);
- if (ftpFileArr == null || ftpFileArr.length == 0) {
- return removeDirectory(path);
- }
- //
- for (int i=ftpFileArr.length ; i>0 ; i-- ) {
- FTPFile ftpFile = ftpFileArr[i-1] ;
- String name = ftpFile.getName();
- if (ftpFile.isDirectory()) {
- System.out.println("* [sD]Delete subPath ["+path + "/" + name+"]");
- removeDirectory(path + "/" + name, true);
- } else if (ftpFile.isFile()) {
- System.out.println("* [sF]Delete file ["+path + "/" + name+"]");
- deleteFile(path + "/" + name);
- }
- // else if (ftpFile.isSymbolicLink()) {
- //
- // } else if (ftpFile.isUnknown()) {
- //
- // }
- }
- return ftpClient.removeDirectory(path);
- }
- public boolean deleteFile(String pathName) throws IOException {
- return ftpClient.deleteFile(pathName);
- }
- public List getFileList(String path) throws IOException {
- FTPFile[] ftpFiles= ftpClient.listFiles(path);
- List retList = new ArrayList();
- if (ftpFiles == null || ftpFiles.length == 0) {
- return retList;
- }
- for (int i=ftpFiles.length ; i>0 ; i-- ) {
- FTPFile ftpFile = ftpFiles[i-1] ;
- if (ftpFile.isFile()) {
- retList.add(ftpFile.getName());
- }
- }
- return retList;
- }
- private void changeWordDir(String wd) throws IOException{
- if(wd != null && wd != ""){
- if(!ftpClient.changeWorkingDirectory(wd)){
- ftpClient.makeDirectory(wd);
- ftpClient.changeWorkingDirectory(wd);
- }
- }
- }
- /**
- * 上传文件到服务器上
- * @param is 文件流
- * @param filepath FTP服务器上文件路径
- * @param filename 文件名称
- * @return
- * @throws Exception
- */
- public boolean uploadFile(InputStream is,String filepath,String filename) throws Exception{
- if(!ftpClient.isConnected()){
- connectToServer();
- }
- changeWordDir(this.workDir);
- changeWordDir(filepath);
- ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
- ftpClient.enterLocalPassiveMode();
- boolean isSuccess = ftpClient.storeFile(filename, is);
- if(isSuccess){
- System.out.println("<-- INFO:upload "+workDir+"/"+filepath+"/"+filename+" from ftp: succeed -->");
- }else{
- System.out.println("<-- INFO:upload "+workDir+"/"+filepath+"/"+filename+" from ftp: failed -->");
- }
- is.close();
- closeConnect();
- return isSuccess;
- }
- /**
- * 从FTP服务器上下载文件
- * @param filepath FTP服务器文件路径
- * @param filename 文件名称
- * @param localPath 本机文件路径
- * @return
- * @throws IOException
- */
- public boolean downLoadFile(String filepath,String filename,String localPath) throws IOException{
- if(!ftpClient.isConnected()){
- connectToServer();
- }
- changeWordDir(this.workDir);
- changeWordDir(filepath);
- if(ftpClient.listNames(filename).length > 0){
- setFileType(FTP.BINARY_FILE_TYPE);
- File localFile = new File(localPath+"/"+filename);
- OutputStream os = new FileOutputStream(localFile);
- boolean isSuccess = ftpClient.retrieveFile(filename, os);
- if(isSuccess){
- System.out.println("<-- INFO:download "+workDir+"/"+filepath+"/"+filename+" from ftp: succeed -->");
- }else{
- System.out.println("<-- INFO:download "+workDir+"/"+filepath+"/"+filename+" from ftp: failed -->");
- }
- os.close();
- closeConnect();
- return isSuccess;
- }else{
- System.out.println("<-- INFO:download "+workDir+"/"+filepath+"/"+filename+" from ftp: failed, file is not exist -->");
- }
- closeConnect();
- return false;
- }
- /**
- * 删除FTP服务器上的文件
- * @param filepath 文件路径
- * @param filename 文件名称
- * @throws IOException
- */
- public boolean deleteFile(String filepath,String filename) throws IOException{
- if(!ftpClient.isConnected()){
- connectToServer();
- }
- changeWordDir(this.workDir);
- changeWordDir(filepath);
- boolean isSuccess = false;
- if(ftpClient.listNames(filename).length > 0){
- isSuccess = ftpClient.deleteFile(filename);
- if(isSuccess){
- System.out.println("<-- INFO:delete "+workDir+"/"+filepath+"/"+filename+" from ftp: succeed -->");
- }else{
- System.out.println("<-- INFO:delete "+workDir+"/"+filepath+"/"+filename+" from ftp: failed -->");
- }
- }else{
- System.out.println("<-- INFO:delete "+workDir+"/"+filepath+"/"+filename+" from ftp: failed, file is not exist -->");
- }
- closeConnect();
- return isSuccess;
- }
- /**
- * download ftp .gz file as BufferedReader
- * @param remoteFileName
- * @return
- * @throws IOException
- */
- public BufferedReader downloadGZFile(
- String remoteFileName, String filePath) throws IOException {
- BufferedReader returnValue = null;
- //下载文件
- BufferedOutputStream buffOut = null;
- try {
- //连接ftp服务器
- connectToServer();
- if (!checkFileExist(filePath, remoteFileName)) {
- System.out.println("<----------- ERR : file " + filePath + "/" + remoteFileName+ " does not exist, download failed!----------->");
- return null;
- } else {
- changeDir( filePath ) ;
- String[] fileNames = ftpClient.listNames();
- //设置传输二进制文件
- setFileType(FTP.BINARY_FILE_TYPE);
- //获得服务器文件
- InputStream in = new GZIPInputStream(ftpClient.retrieveFileStream(remoteFileName));
- //输出操作结果信息
- if (in != null) {
- returnValue = new BufferedReader(new InputStreamReader(in));
- in.close();
- System.out.println("<----------- INFO: download "+ filePath + "/" + remoteFileName+ " from ftp : succeed! ----------->");
- } else {
- System.out.println("<----------- ERR : download "+ filePath + "/" + remoteFileName+ " from ftp : failed! ----------->");
- }
- }
- //关闭连接
- closeConnect();
- } catch (Exception e) {
- e.printStackTrace();
- returnValue = null;
- //输出操作结果信息
- System.out.println("<----------- ERR : download " + filePath + "/" + remoteFileName+ " from ftp : failed! ----------->");
- } finally {
- try {
- if (ftpClient.isConnected()) {
- closeConnect();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return returnValue;
- }
- public String getWorkDir()
- {
- return this.workDir;
- }
- }
- reader.close();
sftp,ftp文件下载的更多相关文章
- Sublime text3 连接sftp/ftp(远程服务器)
1.按下Ctrl + Shift + P调出命令面板2.在输入框中输入Sftp,按回车下载3.建一个新的文件夹放到左边的项目栏中4.右击文件夹,选中SFTP/FTP,点击Map to Remote5. ...
- Sublime Text下使用SFTP/FTP插件
一.前言 本文主要记录了Sublime Text编辑器下的SFTP/FTP的安装使用,方便linux和windows下的文件编辑,只是简单的记录,有不足之处,还望指教. 二.Linux和windows ...
- sftp ftp文件同步方案
sftp ftp文件同步方案 1. 需求 1.1实现网关服务器的ftp服务器的/batchFileRequest目录下文件向徽商所使用的sftp服务器的/batchFileRequest目录同步文件 ...
- Gradle之FTP文件下载
Gradle之FTP文件下载 1.背景 项目上需要使用本地web,所以我们直接将web直接放入assets资源文件夹下.但是随着开发进行web包越来越大:所以我们想着从版本库里面去掉web将其忽略掉, ...
- 【转】JSch - Java实现的SFTP(文件下载详解篇)
上一篇讲述了使用JSch实现文件上传的功能,这一篇主要讲述一下JSch实现文件下载的功能.并介绍一些SFTP的辅助方法,如cd,ls等. 同样,JSch的文件下载也支持三种传输模式:OVERWRI ...
- JSch - Java实现的SFTP(文件下载详解篇)
上一篇讲述了使用JSch实现文件上传的功能,这一篇主要讲述一下JSch实现文件下载的功能.并介绍一些SFTP的辅助方法,如cd,ls等. 同样,JSch的文件下载也支持三种传输模式:OVERWRITE ...
- JSch - Java实现的SFTP(文件下载详解篇)(转)
上一篇讲述了使用JSch实现文件上传的功能,这一篇主要讲述一下JSch实现文件下载的功能.并介绍一些SFTP的辅助方法,如cd,ls等. 同样,JSch的文件下载也支持三种传输模式:OVERWRI ...
- java实现FTP文件下载
package com.vingsoft.util;/*** @author 作者:dujj* @version 创建时间:2020年1月13日 下午5:53:39*/import java.io.F ...
- 【Web】Sublime Text 3 连接sftp/ftp(远程服务器)
在 Win 下常用 Xftp 软件来和远程服务传递文件,但是要是在项目开发的时候频繁的将远程文件拖到本地编辑然后再传回远程服务器,那真是麻烦无比,但是Sublime中SFTP插件,它让这世界美好了许多 ...
随机推荐
- python-flask模块注入(SSTI)
前言: 第一次遇到python模块注入是做ctf的时候,当时并没有搞懂原理所在,看了网上的资料,这里做一个笔记. flask基础: 先看一段python代码: from flask import fl ...
- Window Api 通过账号密码访问共享文件夹
using System; using System.Runtime.InteropServices; namespace PushGCodeService { public class Shared ...
- 请求筛选模块被配置为拒绝包含双重转义序列的请求(.net core程序的‘web.config’调整)
之前项目有一个静态文件特殊字符转义的报错(+变为 %2B),老是显示404 请求筛选模块被配置为拒绝包含双重转义序列的请求 .网上的大多数解决方案都是一下: https://www.cnblogs ...
- JavaScript DOM–事件操作
事件 注册事件 给元素添加事件,为注册事件或者绑定事件 注册事件两种方式 传统方式 监听事件方式 事件监听 addEventListener() 事件监听 (IE9以上) eventTarget.ad ...
- ImportError: libzmq.so.5 报错
https://pkgs.org/download/libzmq.so.5()(64bit) # rpm -ivh zeromq-4.1.4-6.el7.x86_64.rpm
- css代码实现switch开关滑动
效果预览: 代码如下: <style> #toggle-button{ display: none; } .button-label{ position: relative; displa ...
- 在RYU中实现交换机的功能
首先源码,解析部分如下,同时可以参考RYU_BOOK上的解释说明 原文链接参考:https://blog.csdn.net/qq_34099967/article/details/89047741 ...
- [AH2017/HNOI2017] 影魔 - 线段树
#include<bits/stdc++.h> #define maxn 200010 using namespace std; int a[maxn],st[maxn][2],top,L ...
- ActiveMQ注意事项
1.消费者在消费数据的过程当中报错,那么就会自动重试 2.如果消费者报错,会自动重试,但是数据已经真实拿到,可能会造成重复消费,幂等性问题 思路,每一次监听到数据后 ...
- java学习笔记之集合—ArrayList源码解析
1.ArrayList简介 ArrayList是一个数组队列,与java中的数组的容量固定不同,它可以动态的实现容量的增涨.所以ArrayList也叫动态数组.当我们知道有多少个数据元素的时候,我们用 ...