精华内容
下载资源
问答
  • FTP 工具类

    2018-09-07 12:11:45
    FTP 工具类,赚钱积分下载东西,谢谢各位!谢谢各位!
  • java操作FTP工具类

    2015-05-10 22:36:49
    java操作FTP工具类:实现基本断点上传下载、实现上传下载进度汇报、实现中文目录创建及中文文件创建,添加对于中文的支持
  • org.apache.commons.net.ftp.FTPClient FTP工具类,实现上传、下载、压缩到输出流下载等功能
  • 包含文件上传,文件删除,文件列表,查询当天文件表方法; 已经填坑,第一个上传的里面获取指定路径下输入流集合会有空对象;此坑已填
  • FTP工具类

    千次阅读 2020-09-29 23:47:14
    } /** * 创建ftp连接 **/ public static Ftp create() { Ftp ftp = null; try { port = Objects.isNull(port) ? Ftp.DEFAULT_PORT : port; ftp = StringUtils.isEmpty(user) && StringUtils.isEmpty(pwd) ? new Ftp...

    一、依赖

            <dependency>
                <groupId>cn.hutool</groupId>
                <artifactId>hutool-all</artifactId>
                <version>5.3.10</version>
            </dependency>
    
            <dependency>
                <groupId>commons-net</groupId>
                <artifactId>commons-net</artifactId>
                <version>3.6</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.52</version>
            </dependency>
    

    二、代码

    import cn.hutool.extra.ftp.Ftp;
    import com.alibaba.fastjson.JSON;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang.StringUtils;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    import org.springframework.util.CollectionUtils;
    
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Objects;
    
    @Slf4j
    @Component
    public class FTPUtil {
    
        private static String host;
        private static Integer port;
        private static String user;
        private static String pwd;
    
        @Value("${ftp.host}")
        public void setHost(String host) {
            FTPUtil.host = host;
        }
    
        @Value("${ftp.port}")
        public void setPort(Integer port) {
            FTPUtil.port = port;
        }
    
        @Value("${ftp.user}")
        public void setUser(String user) {
            FTPUtil.user = user;
        }
    
        @Value("${ftp.pwd}")
        public void setPwd(String pwd) {
            FTPUtil.pwd = pwd;
        }
    
    
        /**
         * 创建ftp连接
         **/
        public static Ftp create() {
            Ftp ftp = null;
            try {
                port = Objects.isNull(port) ? Ftp.DEFAULT_PORT : port;
                ftp = StringUtils.isEmpty(user) && StringUtils.isEmpty(pwd)
                        ? new Ftp(host, port)
                        : new Ftp(host, port, user, pwd);
            }catch (Exception e){
                log.error("创建ftp链接失败:{}",e);
            }
            if (ftp == null) {
                throw new RuntimeException("连接FTP服务器失败,请检查配置是否正确");
            }
            //防止客户端读取文件为空
            ftp.getClient().enterLocalPassiveMode();
            return ftp;
        }
    
    
        /**
         * ftp文件批量下载
         **/
        public static List<File> download(Ftp ftp, String path) {
            try {
                List<File> files = new ArrayList<>();
                ftp.cd(path);
                List<String> ftpFiles = ftp.ls(ftp.pwd());
                log.info("文件列表为{}", JSON.toJSONString(ftpFiles));
                if (!CollectionUtils.isEmpty(ftpFiles)) {
                    ftpFiles.stream().forEach(e->{
                        //新建文件
                        File file = new File(e);
                        if (!file.exists()) {
                            if (!Objects.isNull(file.getParentFile()) &&
                                    !file.getParentFile().exists()) {
                                file.getParentFile().mkdirs();
                            }
                            try {
                                file.createNewFile();
                            } catch (IOException ex) {
                                log.error("创建文件异常:{}",e);
                            }
                        }
                        ftp.download(path, e, file);
                        files.add(file);
                    });
                    return files;
                }
            } catch (Exception e) {
                log.error("批量下载文件异常:{}",e);
            }
            return null;
        }
    
        /**
         * ftp文件上传
         **/
        public static boolean upload(Ftp ftp, String fileName, String path, File file) {
            if (StringUtils.isEmpty(path)) {
                return false;
            }
            if (!ftp.exist(path)) {
                ftp.mkdir(path);
            }
            ftp.upload(path, fileName, file);
            ftp.toParent();
            return true;
        }
    
        /**
         * 上传InputStream文件
         **/
        public static boolean uploadRecord(Ftp ftp, String fileName, String path, InputStream inputStream) {
            try {
                if (!ftp.exist(path)) {
                    ftp.mkDirs(path);
                }
                // 目录存在开始上传
                if (ftp.exist(path)) {
                    ftp.upload(path, fileName, inputStream);
                }
            } catch (Exception e) {
                log.error("文件上传失败: {}",e);
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                       log.error("关闭InputStream失败:{}", e);
                    }
                }
                close(ftp);
            }
            return true;
        }
    
    
        /**
         * 关闭ftp连接
         **/
        public static void close(Ftp ftp) {
            try {
                if (!Objects.isNull(ftp)) {
                    ftp.close();//断开连接
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    }
    
    展开全文
  • JAVA操作FTP(FTP工具类

    千次阅读 2020-06-16 00:24:04
    JAVA FTP操作 导入commons-net <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.6</version> </dependency> ...

    Java 操作 FTP、FTP工具类、Java实现FTP代码示例

    导入commons-net

    <dependency>
        <groupId>commons-net</groupId>
        <artifactId>commons-net</artifactId>
        <version>3.6</version>
    </dependency>
    
    package com.my.ftp.test;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    import java.util.StringTokenizer;
    
    import org.apache.commons.net.ftp.FTP;
    import org.apache.commons.net.ftp.FTPClient;
    import org.apache.commons.net.ftp.FTPClientConfig;
    import org.apache.commons.net.ftp.FTPFile;
    import org.apache.commons.net.ftp.FTPReply;
    
    public class Ftp {
    
    	private String Control_Encoding = "UTF-8";
    
    	private FTPClient client = null;
    
    	private String host = "";
    	private int port = 21;
    	private String user = "";
    	private String password = "";
    	private String ftpPath = "/";
    
    	@SuppressWarnings("unused")
    	private Ftp() {
    	}
    
    	public Ftp(String host, int port, String user, String pwd) {
    		this.host = host;
    		this.port = port;
    		this.user = user;
    		this.password = pwd;
    	}
    
    	/**
    	 * 获取当前FTP所在目录位置
    	 * 
    	 * @return
    	 */
    	public String getHome() {
    		return this.ftpPath;
    	}
    
    	/**
    	 * 连接FTP Server
    	 * 
    	 * @throws IOException
    	 */
    	public static final String ANONYMOUS_USER = "anonymous";
    
    	public void connect() throws Exception {
    		if (client == null) {
    			client = new FTPClient();
    		}
    		// 已经连接
    		if (client.isConnected()) {
    			return;
    		}
    
    		// 编码
    		client.setControlEncoding(Control_Encoding);
    
    		try {
    			// 连接FTP Server
    			client.connect(this.host, this.port);
    			// 登陆
    			if (this.user == null || "".equals(this.user)) {
    				// 使用匿名登陆
    				client.login(ANONYMOUS_USER, ANONYMOUS_USER);
    			} else {
    				client.login(this.user, this.password);
    			}
    			// 设置文件格式
    			client.setFileType(FTPClient.BINARY_FILE_TYPE);
    			// 获取FTP Server 应答
    			int reply = client.getReplyCode();
    			if (!FTPReply.isPositiveCompletion(reply)) {
    				client.disconnect();
    				throw new Exception("connection FTP fail!");
    			}
    
    			FTPClientConfig config = new FTPClientConfig(client.getSystemType().split(" ")[0]);
    			config.setServerLanguageCode("zh");
    			client.configure(config);
    			// 使用被动模式设为默认
    			client.enterLocalPassiveMode();
    			// 二进制文件支持
    			client.setFileType(FTP.BINARY_FILE_TYPE);
    			// 设置模式
    			client.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
    
    		} catch (IOException e) {
    			throw new Exception("connection FTP fail! " + e);
    		}
    	}
    
    	/**
    	 * 断开FTP连接
    	 * 
    	 * @param ftpClient
    	 * @throws IOException
    	 */
    	public void close() {
    		if (client != null && client.isConnected()) {
    			try {
    				client.logout();
    				client.disconnect();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    
    	/**
    	 * 获取文件列表
    	 * 
    	 * @return
    	 */
    	public List<FTPFile> list() {
    		List<FTPFile> list = null;
    		try {
    			FTPFile ff[] = client.listFiles(ftpPath);
    			if (ff != null && ff.length > 0) {
    				list = new ArrayList<FTPFile>(ff.length);
    				Collections.addAll(list, ff);
    			} else {
    				list = new ArrayList<FTPFile>(0);
    			}
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return list;
    	}
    
    	/**
    	 * 切换目录
    	 * 
    	 * @param path
    	 *            需要切换的目录
    	 * @param forcedIncrease
    	 *            如果目录不存在,是否增加
    	 */
    	public void switchDirectory(String path, boolean forcedIncrease) {
    		try {
    			if (path != null && !"".equals(path)) {
    				boolean ok = client.changeWorkingDirectory(path);
    				if (ok) {
    					this.ftpPath = path;
    				} else if (forcedIncrease) {
    					// ftpPath 不存在,手动创建目录
    					StringTokenizer token = new StringTokenizer(path, "\\//");
    					while (token.hasMoreTokens()) {
    						String npath = token.nextToken();
    						client.makeDirectory(npath);
    						client.changeWorkingDirectory(npath);
    						if (ok) {
    							this.ftpPath = path;
    						}
    					}
    				}
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    
    	/**
    	 * 创建目录
    	 * 
    	 * @param path
    	 */
    	public void createDirectory(String path) {
    		try {
    			if (path != null && !"".equals(path)) {
    				boolean ok = client.changeWorkingDirectory(path);
    				if (!ok) {
    					// ftpPath 不存在,手动创建目录
    					StringTokenizer token = new StringTokenizer(path, "\\//");
    					while (token.hasMoreTokens()) {
    						String npath = token.nextToken();
    						client.makeDirectory(npath);
    						client.changeWorkingDirectory(npath);
    					}
    				}
    			}
    			client.changeWorkingDirectory(this.ftpPath);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    
    	/**
    	 * 删除目录,如果目录中存在文件或者文件夹则删除失败
    	 * 
    	 * @param path
    	 * @return
    	 */
    	public boolean deleteDirectory(String path) {
    		boolean flag = false;
    		try {
    			flag = client.removeDirectory(path);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return flag;
    	}
    
    	/**
    	 * 删除文件
    	 * 
    	 * @param path
    	 * @return
    	 */
    	public boolean deleteFile(String path) {
    		boolean flag = false;
    		try {
    			flag = client.deleteFile(path);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return flag;
    	}
    
    	/**
    	 * 上传文件,上传文件只会传到当前所在目录
    	 * 
    	 * @param localFile
    	 *            本地文件
    	 * @return
    	 */
    	public boolean upload(File localFile) {
    		return this.upload(localFile, "");
    	}
    
    	/**
    	 * 上传文件,会覆盖FTP上原有文件
    	 * 
    	 * @param localFile
    	 *            本地文件
    	 * @param reName
    	 *            重名
    	 * @return
    	 */
    	public boolean upload(File localFile, String reName) {
    		boolean flag = false;
    		String targetName = reName;
    		// 设置上传后文件名
    		if (reName == null || "".equals(reName)) {
    			targetName = localFile.getName();
    		}
    		FileInputStream fis = null;
    		try {
    			// 开始上传文件
    			fis = new FileInputStream(localFile);
    			client.setControlEncoding(Control_Encoding);
    			client.setFileType(FTPClient.BINARY_FILE_TYPE);
    			boolean ok = client.storeFile(targetName, fis);
    			if (ok) {
    				flag = true;
    			}
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return flag;
    	}
    
    	/**
    	 * 下载文件,如果存在会覆盖原文件
    	 * 
    	 * @param ftpFileName
    	 *            文件名称,FTP上的文件名称
    	 * @param savePath
    	 *            保存目录,本地保存目录
    	 * @return
    	 */
    	public boolean download(String ftpFileName, String savePath) {
    		boolean flag = false;
    
    		File dir = new File(savePath);
    
    		if (!dir.exists()) {
    			dir.mkdirs();
    		}
    
    		FileOutputStream fos = null;
    		try {
    			String saveFile = dir.getAbsolutePath() + File.separator + ftpFileName;
    			fos = new FileOutputStream(new File(saveFile));
    			boolean ok = client.retrieveFile(ftpFileName, fos);
    			if (ok) {
    				flag = true;
    			}
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return flag;
    	}
    
    	public static void main(String args[]) {
    
    		// 创建FTP对象
    		Ftp ftp = new Ftp("127.0.0.1", 21, "myftp", "myftp@2020");
    		try {
    			// 连接FTP
    			ftp.connect();
    
    			// 移动工作空间、切换目录
    			System.out.println("当前位置:" + ftp.getHome());
    			ftp.switchDirectory("/test", true);
    			System.out.println("当前位置:" + ftp.getHome());
    
    			// 查询目录下的所有文件夹以及文件
    			List<FTPFile> list = ftp.list();
    			System.out.println("|-- " + ftp.getHome());
    			for (FTPFile f : list) {
    				System.out.println(" |-- [" + (f.getType() == 0 ? "文件" : "文件夹") + "]" + f.getName());
    			}
    
    			// 上传文件
    			boolean r1 = ftp.upload(new File("C:\\Users\\joymt\\Documents\\ftp\\测试文件1.txt"), "测试文件2.txt");
    			System.out.println("上传文件:" + r1);
    
    			// 下载文件
    			boolean r2 = ftp.download("测试文件2.txt", "C:\\Users\\joymt\\Documents\\ftp");
    			System.out.println("下载文件:" + r2);
    
    			// 删除文件
    			boolean r3 = ftp.deleteFile("/test/测试文件2.txt");
    			System.out.println("删除文件:" + r3);
    
    			// 删除目录
    			boolean r4 = ftp.deleteDirectory("/test");
    			System.out.println("删除目录:" + r4);
    
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    
    		ftp.close();
    	}
    
    }
    
    展开全文
  • java ftp工具类源码

    2020-09-02 20:02:14
    java ftp文件传输工具类源码 依赖包 <!-- https://mvnrepository.com/artifact/commons-net/commons-net --> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.7 ...
  • ftp工具类,包含文件上传,文件删除,文件列表,查询当天文件类表方法
  • jdk1.7以上专用FTP工具类,本人花了半天时间调试通过,拿来即用,具体用法详见main函数。
  • 这里已经忘了参考的哪位博友的文章,如果有哪位小伙伴看到,请留言Ftp工具类package com.ldl.test.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io....

    这里已经忘了参考的哪位博友的文章,如果有哪位小伙伴看到,请留言

    Ftp工具类

    package com.ldl.test.util;
    
    import java.io.BufferedInputStream;  
    import java.io.BufferedOutputStream;  
    import java.io.ByteArrayOutputStream;  
    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.SocketException;  
    import java.net.UnknownHostException;  
    import java.util.ArrayList;  
    import java.util.List;  
      
    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;  
      
    /** 
     * FTPClient工具类 
     * @author ldl 
     */  
    public class FtpUtil {  
          
        //private static Logger log = Logger.getLogger(FtpUtil.class);  
        private FTPClient ftp;  
      
        public FtpUtil() {  
            ftp = new FTPClient();  
            ftp.setControlEncoding("UTF-8"); //解决上传文件时文件名乱码  
        }  
          
        public FtpUtil(String controlEncoding) {  
            ftp = new FTPClient();  
            ftp.setControlEncoding(controlEncoding); //解决上传文件时文件名乱码  
        }  
          
        public void setTimeOut(int defaultTimeoutSecond, int connectTimeoutSecond, int dataTimeoutSecond){  
            try {  
                ftp.setDefaultTimeout(defaultTimeoutSecond * 1000);  
                //ftp.setConnectTimeout(connectTimeoutSecond * 1000); //commons-net-3.5.jar  
                ftp.setSoTimeout(connectTimeoutSecond * 1000); //commons-net-1.4.1.jar 连接后才能设置  
                ftp.setDataTimeout(dataTimeoutSecond * 1000);  
            } catch (SocketException e) { 
            	System.out.println("setTimeout Exception:"+e);
            }  
        }  
          
        public FTPClient getFTPClient(){  
            return ftp;  
        }  
          
        public void setControlEncoding(String charset){  
            ftp.setControlEncoding(charset);  
        }  
          
        public void setFileType(int fileType) throws IOException {  
            ftp.setFileType(fileType);  
        }  
      
        /** 
         * Connect to FTP server. 
         *  
         * @param host 
         *            FTP server address or name 
         * @param port 
         *            FTP server port 
         * @param user 
         *            user name 
         * @param password 
         *            user password 
         * @throws IOException 
         *             on I/O errors 
         */  
        public FTPClient connect(String host, int port, String user, String password) throws IOException {  
            // Connect to server.  
            try {  
                ftp.connect(host, port);  
            } catch (UnknownHostException ex) {  
                throw new IOException("Can't find FTP server '" + host + "'");  
            }  
      
            // Check rsponse after connection attempt.  
            int reply = ftp.getReplyCode();  
            if (!FTPReply.isPositiveCompletion(reply)) {  
                disconnect();  
                throw new IOException("Can't connect to server '" + host + "'");  
            }  
      
            if ("".equals(user)) {  
                user = "qiangdiao_ftp";  
            }  
      
            // Login.  
            if (!ftp.login(user, password)) {  
                disconnect();  
                throw new IOException("Can't login to server '" + host + "'");  
            }  
      
            // Set data transfer mode.  
            ftp.setFileType(FTP.BINARY_FILE_TYPE);  
            //ftp.setFileType(FTP.ASCII_FILE_TYPE);  
              
            /*  注: ftp上传到服务器分主动模式和被动模式,网ip上传主动模式:ftp.enterLocalActiveMode();(默认)
            	内网ip上传被动模式:ftp.enterLocalPassiveMode();*/
            // Use passive mode to pass firewalls.  
            //ftp.enterLocalPassiveMode();  
              
            return ftp;  
        }  
          
        /** 
         * Test connection to ftp server 
         *  
         * @return true, if connected 
         */  
        public boolean isConnected() {  
            return ftp.isConnected();  
        }  
          
        /** 
         * Disconnect from the FTP server 
         *  
         * @throws IOException 
         *             on I/O errors 
         */  
        public void disconnect() throws IOException {  
      
            if (ftp.isConnected()) {  
                try {  
                    ftp.logout();  
                    ftp.disconnect();  
                } catch (IOException ex) {  
                }  
            }  
        }  
          
        /** 
         * Get file from ftp server into given output stream 
         *  
         * @param ftpFileName 
         *            file name on ftp server 
         * @param out 
         *            OutputStream 
         * @throws IOException 
         */  
        public void retrieveFile(String ftpFileName, OutputStream out) throws IOException {  
            try {  
                // Get file info.  
                FTPFile[] fileInfoArray = ftp.listFiles(ftpFileName);  
                if (fileInfoArray == null || fileInfoArray.length == 0) {  
                    throw new FileNotFoundException("File '" + ftpFileName + "' was not found on FTP server.");  
                }  
      
                // Check file size.  
                FTPFile fileInfo = fileInfoArray[0];  
                long size = fileInfo.getSize();  
                if (size > Integer.MAX_VALUE) {  
                    throw new IOException("File '" + ftpFileName + "' is too large.");  
                }  
      
                // Download file.  
                if (!ftp.retrieveFile(ftpFileName, out)) {  
                    throw new IOException("Error loading file '" + ftpFileName + "' from FTP server. Check FTP permissions and path.");  
                }  
      
                out.flush();  
      
            } finally {  
                if (out != null) {  
                    try {  
                        out.close();  
                    } catch (IOException ex) {  
                    }  
                }  
            }  
        }  
      
        /** 
         * Put file on ftp server from given input stream 
         *  
         * @param ftpFileName 
         *            file name on ftp server 
         * @param in 
         *            InputStream 
         * @throws IOException 
         */  
        public void storeFile(String ftpFileName, InputStream in) throws IOException {  
            try {  
                if (!ftp.storeFile(ftpFileName, in)) {  
                    throw new IOException("Can't upload file '" + ftpFileName + "' to FTP server. Check FTP permissions and path.");  
                }  
            } finally {  
                try {  
                    in.close();  
                } catch (IOException ex) {  
                }  
            }  
        }  
          
        /** 
         * 修改名称 
         * @param from 
         * @param to 
         * @throws IOException 
         */  
        public boolean rename(String from, String to) throws IOException {  
            return ftp.rename(from, to);  
        }  
          
        /** 
         * Delete the file from the FTP server. 
         *  
         * @param ftpFileName 
         *            server file name (with absolute path) 
         * @throws IOException 
         *             on I/O errors 
         */  
        public void deleteFile(String ftpFileName) throws IOException {  
            if (!ftp.deleteFile(ftpFileName)) {  
                throw new IOException("Can't remove file '" + ftpFileName + "' from FTP server.");  
            }  
        }  
      
        /** 
         * Upload the file to the FTP server. 
         *  
         * @param ftpFileName 
         *            server file name (with absolute path) 
         * @param localFile 
         *            local file to upload 
         * @throws IOException 
         *             on I/O errors 
         */  
        public void upload(String ftpFileName, File localFile) throws IOException { 
            // File check.  
            if (!localFile.exists()) {  
                throw new IOException("Can't upload '" + localFile.getAbsolutePath() + "'. This file doesn't exist.");  
            }  
      
            // Upload.  
            InputStream in = null;  
            try {  
                in = new BufferedInputStream(new FileInputStream(localFile)); 
                if (!ftp.storeFile(ftpFileName, in)) {  
                    throw new IOException("Can't upload file '" + ftpFileName + "' to FTP server. Check FTP permissions and path.");  
                }  
      
            } finally {  
                try {  
                    in.close();  
                } catch (IOException ex) {
                	ex.printStackTrace();
                }  
            }  
        }  
          
        /** 
         * 上传目录(会覆盖) 
         * @param remotePath 远程目录 /home/test/a 
         * @param localPath 本地目录 D:/test/a 
         * @throws IOException 
         */  
        public void uploadDir(String remotePath, String localPath) throws IOException {  
            File file = new File(localPath);  
            if (file.exists()) {  
                if(!ftp.changeWorkingDirectory(remotePath)){  
                    ftp.makeDirectory(remotePath);  //创建成功返回true,失败(已存在)返回false  
                    ftp.changeWorkingDirectory(remotePath); //切换成返回true,失败(不存在)返回false  
                }  
                File[] files = file.listFiles();  
                for (File f : files) {  
                    if (f.isDirectory() && !f.getName().equals(".") && !f.getName().equals("..")) {  
                        uploadDir(remotePath + File.separator + f.getName(), f.getPath());  
                    } else if (f.isFile()) {  
                        upload(remotePath + File.separator + f.getName(), f);  
                    }  
                }  
            }  
        }  
      
        /** 
         * Download the file from the FTP server. 
         *  
         * @param ftpFileName 
         *            server file name (with absolute path) 
         * @param localFile 
         *            local file to download into 
         * @throws IOException 
         *             on I/O errors 
         */  
        public void download(String ftpFileName, File localFile) throws IOException {  
            // Download.  
            OutputStream out = null;  
            try {  
                // Get file info.  
                FTPFile[] fileInfoArray = ftp.listFiles(ftpFileName);  
                if (fileInfoArray == null || fileInfoArray.length == 0) {  
                    throw new FileNotFoundException("File " + ftpFileName + " was not found on FTP server.");  
                }  
      
                // Check file size.  
                FTPFile fileInfo = fileInfoArray[0];  
                long size = fileInfo.getSize();  
                if (size > Integer.MAX_VALUE) {  
                    throw new IOException("File " + ftpFileName + " is too large.");  
                }  
      
                // Download file.  
                out = new BufferedOutputStream(new FileOutputStream(localFile));  
                if (!ftp.retrieveFile(ftpFileName, out)) {  
                    throw new IOException("Error loading file " + ftpFileName + " from FTP server. Check FTP permissions and path.");  
                }  
      
                out.flush();  
            } finally {  
                if (out != null) {  
                    try {  
                        out.close();  
                    } catch (IOException ex) {  
                    }  
                }  
            }  
        }  
          
        /** 
         * 下载目录(会覆盖) 
         * @param remotePath 远程目录 /home/test/a 
         * @param localPath 本地目录 D:/test/a 
         * @return 
         * @throws IOException 
         */  
        public void downloadDir(String remotePath, String localPath) throws IOException {  
            File file = new File(localPath);  
            if(!file.exists()){  
                file.mkdirs();  
            }  
            FTPFile[] ftpFiles = ftp.listFiles(remotePath);  
            for (int i = 0; ftpFiles!=null && i<ftpFiles.length; i++) {  
                FTPFile ftpFile = ftpFiles[i];  
                if (ftpFile.isDirectory() && !ftpFile.getName().equals(".") && !ftpFile.getName().equals("..")) {  
                    downloadDir(remotePath + File.separator + ftpFile.getName(), localPath + File.separator + ftpFile.getName());  
                } else {  
                    download(remotePath + File.separator + ftpFile.getName(), new File(localPath + File.separator + ftpFile.getName()));  
                }  
            }  
        }  
      
        /** 
         * List the file name in the given FTP directory. 
         *  
         * @param filePath 
         *            absolute path on the server 
         * @return files relative names list 
         * @throws IOException 
         *             on I/O errors 
         */  
        public List<String> listFileNames(String filePath) throws IOException {  
            List<String> fileList = new ArrayList<String>();  
      
            FTPFile[] ftpFiles = ftp.listFiles(filePath);  
            for (int i = 0; ftpFiles!=null && i<ftpFiles.length; i++) {  
                FTPFile ftpFile = ftpFiles[i];  
                if (ftpFile.isFile()) {  
                    fileList.add(ftpFile.getName());  
                }  
            }  
              
            return fileList;  
        }  
          
        /** 
         * List the files in the given FTP directory. 
         *  
         * @param filePath 
         *            directory 
         * @return list 
         * @throws IOException 
         */  
        public List<FTPFile> listFiles(String filePath) throws IOException {  
            List<FTPFile> fileList = new ArrayList<FTPFile>();  
      
            FTPFile[] ftpFiles = ftp.listFiles(filePath);  
            for (int i = 0; ftpFiles!=null && i<ftpFiles.length; i++) {  
                FTPFile ftpFile = ftpFiles[i];  
    //            FfpFileInfo fi = new FfpFileInfo();  
    //            fi.setName(ftpFile.getName());  
    //            fi.setSize(ftpFile.getSize());  
    //            fi.setTimestamp(ftpFile.getTimestamp());  
    //            fi.setType(ftpFile.isDirectory());  
                fileList.add(ftpFile);  
            }  
      
            return fileList;  
        }  
      
      
        /** 
         * Send an FTP Server site specific command 
         *  
         * @param args 
         *            site command arguments 
         * @throws IOException 
         *             on I/O errors 
         */  
        public void sendSiteCommand(String args) throws IOException {  
            if (ftp.isConnected()) {  
                try {  
                    ftp.sendSiteCommand(args);  
                } catch (IOException ex) {  
                }  
            }  
        }  
      
        /** 
         * Get current directory on ftp server 
         *  
         * @return current directory 
         */  
        public String printWorkingDirectory() {  
            if (!ftp.isConnected()) {  
                return "";  
            }  
      
            try {  
                return ftp.printWorkingDirectory();  
            } catch (IOException e) {  
            }  
      
            return "";  
        }  
      
        /** 
         * Set working directory on ftp server 
         *  
         * @param dir 
         *            new working directory 
         * @return true, if working directory changed 
         */  
        public boolean changeWorkingDirectory(String dir) {  
            if (!ftp.isConnected()) {  
                return false;  
            }  
      
            try {  
                return ftp.changeWorkingDirectory(dir);  
            } catch (IOException e) {  
            }  
      
            return false;  
        }  
      
        /** 
         * Change working directory on ftp server to parent directory 
         *  
         * @return true, if working directory changed 
         */  
        public boolean changeToParentDirectory() {  
            if (!ftp.isConnected()) {  
                return false;  
            }  
      
            try {  
                return ftp.changeToParentDirectory();  
            } catch (IOException e) {  
            }  
      
            return false;  
        }  
      
        /** 
         * Get parent directory name on ftp server 
         *  
         * @return parent directory 
         */  
        public String printParentDirectory() {  
            if (!ftp.isConnected()) {  
                return "";  
            }  
      
            String w = printWorkingDirectory();  
            changeToParentDirectory();  
            String p = printWorkingDirectory();  
            changeWorkingDirectory(w);  
      
            return p;  
        }  
          
        /** 
         * 创建目录 
         * @param pathname 
         * @throws IOException 
         */  
        public boolean makeDirectory(String pathname) throws IOException {  
            return ftp.makeDirectory(pathname);  
        }  
        
        /** 
         * 查询ftp服务器上指定路径所有文件名 
         *  
         * @param url 
         *            FTP服务器hostname 
         * @param port 
         *            FTP服务器端口 
         * @param username 
         *            FTP登录账号 
         * @param password 
         *            FTP登录密码 
         * @param remotePath 
         *            FTP服务器上的相对路径 
         * @return 
         */  
        public static List<String> listFTPFiles(String url, int port, String username, String password, String remotePath) {  
            ArrayList<String> resultList = new ArrayList<String>();  
            FTPClient ftp = new FTPClient();  
            try {  
                int reply;  
                ftp.connect(url, port);  
                // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器  
                ftp.login(username, password);// 登录  
                ftp.setFileType(FTPClient.BINARY_FILE_TYPE);  
                reply = ftp.getReplyCode();  
                if (!FTPReply.isPositiveCompletion(reply)) {  
                    ftp.disconnect();  
                    return resultList;  
                }  
                ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录  
                FTPFile[] fs = ftp.listFiles();  
                for (FTPFile ff : fs) {  
                    resultList.add(ff.getName());  
                    // if (ff.getName().equals(fileName)) {  
                    // File localFile = new File(localPath + "/" + ff.getName());  
                    // OutputStream is = new FileOutputStream(localFile);  
                    // ftp.retrieveFile(ff.getName(), is);  
                    // is.close();  
                    // }  
                }  
                ftp.logout();  
            } catch (IOException e) {  
                e.printStackTrace();  
            } finally {  
                if (ftp.isConnected()) {  
                    try {  
                        ftp.disconnect();  
                    } catch (IOException ioe) {  
                    }  
                }  
            }  
            return resultList;  
        }  
          
        /** 
         * 创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建 
         * @param url 
         * @param port 
         * @param username 
         * @param password 
         * @param remote 
         * @return 
         * @throws IOException  
         */  
        public static boolean createDirectory(String url, int port, String username, String password, String remote)  
                throws IOException {  
          
            FTPClient ftp = new FTPClient();  
            int reply;  
            ftp.connect(url, port);  
            // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器  
            ftp.login(username, password);// 登录  
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);  
            reply = ftp.getReplyCode();  
            if (!FTPReply.isPositiveCompletion(reply)) {  
                ftp.disconnect();  
            }  
            //ftp.changeWorkingDirectory("/var/www/html");// 转移到FTP服务器目录  
          
            boolean success = true;  
            String directory = remote + "/";  
            // String directory = remote.substring(0, remote.lastIndexOf("/") + 1);  
            // 如果远程目录不存在,则递归创建远程服务器目录  
            if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory), ftp)) {  
                int start = 0;  
                int end = 0;  
                if (directory.startsWith("/")) {  
                    start = 1;  
                } else {  
                    start = 0;  
                }  
                end = directory.indexOf("/", start);  
                String path = "";  
                String paths = "";  
                while (true) {  
                    String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");  
                    path = path + "/" + subDirectory;  
                    if (!existFile(path, ftp)) {  
                        if (makeDirectory(subDirectory, ftp)) {  
                            changeWorkingDirectory(subDirectory, ftp);  
                        } else {  
                            System.out.println("创建目录[" + subDirectory + "]失败");  
                            changeWorkingDirectory(subDirectory, ftp);  
                        }  
                    } else {  
                        changeWorkingDirectory(subDirectory, ftp);  
                    }  
          
                    paths = paths + "/" + subDirectory;  
                    start = end + 1;  
                    end = directory.indexOf("/", start);  
                    // 检查所有目录是否创建完毕  
                    if (end <= start) {  
                        break;  
                    }  
                }  
            }  
            return success;  
        }  
          
        /** 
         * 改变目录路径 
         * @param directory 
         * @param ftp 
         * @return  
         */  
        public static boolean changeWorkingDirectory(String directory, FTPClient ftp) {  
            boolean flag = true;  
            try {  
                flag = ftp.changeWorkingDirectory(directory);  
                if (flag) {  
                    System.out.println("进入文件夹" + directory + " 成功!");  
                } else {  
                    System.out.println("进入文件夹" + directory + " 失败!");  
                }  
            } catch (IOException ioe) {  
                ioe.printStackTrace();  
            }  
            return flag;  
        }  
          
        /** 
         * 创建目录 
         * @param dir 
         * @param ftp 
         * @return  
         */  
        public static boolean makeDirectory(String dir, FTPClient ftp) {  
            boolean flag = true;  
            try {  
                flag = ftp.makeDirectory(dir);  
                if (flag) {  
                    System.out.println("创建文件夹" + dir + " 成功!");  
                } else {  
                    System.out.println("创建文件夹" + dir + " 失败!");  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
            return flag;  
        }  
          
        /** 
         * 判断ftp服务器文件是否存在 
         * @param path 
         * @param ftp 
         * @return 
         * @throws IOException  
         */  
        public static boolean existFile(String path, FTPClient ftp) throws IOException {  
            boolean flag = false;  
            FTPFile[] ftpFileArr = ftp.listFiles(path);  
            if (ftpFileArr.length > 0) {  
                flag = true;  
            }  
            return flag;  
        }
    }  

    测试类

    package com.ldl.test.controller;
    
    import java.io.File;
    import java.io.IOException;
    
    import com.ldl.test.util.FtpUtil;
    
    public class FtpController {
    
    	public static void main(String[] args) {
    
    		FtpUtil ftpUtil = new FtpUtil("UTF-8");  
            try {
    			ftpUtil.connect("", 21, "qiangdiao_ftp", "qiangdiao_ftp_test");
    			//0871/yidong/action_YYYYMMDD
    	        //ftpUtil.setTimeOut(60, 60, 60);  
    	        /*ftpUtil.upload("/home/testuser/文件1.txt", new File("E:/image/FTPClient/FTPClient测试/文件1.txt"));  
    	        ftpUtil.download("/home/testuser/文件1.txt", new File("E:/image/FTPClient/FTPClient测试/文件1.txt"));  
    	        ftpUtil.uploadDir("/home/testuser/FTPClient测试", "E:/image/FTPClient/FTPClient测试");  
    	        ftpUtil.downloadDir("/home/testuser/FTPClient测试", "E:/image/FTPClient/FTPClient测试"); */ 
    	          
    	        //把远程文件读入到流中
    	        /*ByteArrayOutputStream bos = new ByteArrayOutputStream(); //自动增长  
    	        ftpUtil.retrieveFile("/home/testuser/文件1.txt", bos);  
    	        System.out.println(bos.size());  
    	        String contentStr = new String(bos.toByteArray(),"GBK");  
    	        System.out.println(contentStr);*/  
    			
    			//打印父目录
    			//System.out.println(ftpUtil.printParentDirectory());
    			//打印工作目录
    			//System.out.println(ftpUtil.printWorkingDirectory());
    			
    			//在工作目录下创建目录     注:只能一级一级创建,并要切换目录后才能创建下级目录
    			/*String newDirectory = "0871";
    			ftpUtil.makeDirectory(newDirectory);
    			ftpUtil.changeWorkingDirectory("0871");
    			System.out.println(ftpUtil.printWorkingDirectory());
    			ftpUtil.makeDirectory("yidong");*/
    			
    			/*ftpUtil.changeWorkingDirectory("0871/yidong");//注:切换目录时,不能用文件File.separator,直接用 '/',不然会失败
    			System.out.println(ftpUtil.printWorkingDirectory());*/
    			
            	//封装创建多层目录
            	//System.out.println(ftpUtil.createDirectory("", 21, "qiangdiao_ftp", "qiangdiao_ftp_test", "mutiple/test/haha"));
    			
            	/*System.out.println("------上传开始---------");
            	//切换目录
            	//ftpUtil.changeWorkingDirectory("/home/ftp/qiangdiao/0871/yidong");
            	ftpUtil.upload("/home/ftp/qiangdiao/0871/yidong/action_201806175.zip", new File(System.getProperty("user.dir")+File.separator+"upload"+File.separator+"action_201806175.zip"));  
            	System.out.println("-------上传结束----------");*/
    			
    			//如果没有切换工作目录就要写绝对目录
    			//ftpUtil.download("/home/ftp/qiangdiao/0871/yidong/action_201806175.zip", new File(System.getProperty("user.dir")+File.separator+"upload"+File.separator+"ftp_download.zip"));  
            	
    			ftpUtil.disconnect();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}  
    	}
    
    }
    

    特别注意微笑

              
            /*  注: ftp上传到服务器分主动模式和被动模式,网ip上传主动模式:ftp.enterLocalActiveMode();(默认)
            	内网ip上传被动模式:ftp.enterLocalPassiveMode();*/
            // Use passive mode to pass firewalls.  
            //ftp.enterLocalPassiveMode(); 

    我当时就设置的本地模式,上传文件时会一直报连接超时这个错,如下图

    ftp.enterLocalPassiveMode();
    
    


    项目源码GitHub: https://github.com/MrLiam/FtpDemo
    展开全文
  • ftp操作工具类,用户ftp文件的添加,删除,等操作!
  • ftp工具类,构造方法初始化类,连接ftp,列出所有文件内容,下载文件
  • java连接ftp工具类

    千次阅读 2019-05-25 14:36:50
    这里使用了org.apache.commons.net.ftp这个类库,仅仅是对这个类库稍微封装了一下方便使用,这里写了一个工具类,大家可以参考一下。 依赖 <dependency> <groupId>commons-net</groupId> <...

    这里使用了org.apache.commons.net.ftp这个类库,仅仅是对这个类库稍微封装了一下方便使用,这里写了一个工具类,大家可以参考一下。

    介绍一个 ftp客户端工具:iis7服务器管理工具

    IIs7服务器管理工具可以批量管理ftp站点,同时具备定时上传下载的功能。

    作为服务器集成管理器,它最优秀的功能就是批量管理windows与linux系统服务器、vps。能极大的提高站长及服务器运维人员工作效率。同时iis7服务器管理工具还是vnc客户端,服务器真正实现了一站式管理,可谓是非常方便。
    下载地址:http://yczm.iis7.com/?tscc
    在这里插入图片描述

    依赖

            <dependency>
                <groupId>commons-net</groupId>
                <artifactId>commons-net</artifactId>
                <version>${commons.net.version}</version>
            </dependency>
    

    工具类

    public class FtpUtil {
        /**
         * 维护FTPClient实例
         */
        private final static LinkedBlockingQueue<FTPClient> FTP_CLIENT_QUEUE = new LinkedBlockingQueue<>();
    
        /**
         * 创建目录
         *
         * @param ftpConfig  配置
         * @param remotePath 需要创建目录的目录
         * @param makePath   需要创建的目录
         * @return 是否创建成功
         */
        public static boolean makeDirectory(FtpConfig ftpConfig, String remotePath, String makePath) {
            try {
                FTPClient ftpClient = connectClient(ftpConfig);
                boolean changeResult = ftpClient.changeWorkingDirectory(remotePath);
                if (!changeResult) {
                    throw new RuntimeException("切换目录失败");
                }
                boolean result = ftpClient.makeDirectory(makePath);
                // 退出FTP
                ftpClient.logout();
                //归还对象
                offer(ftpClient);
                return result;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    
        /**
         * 移动文件
         *
         * @param ftpConfig 配置
         * @param fromPath  待移动目录
         * @param fromName  待移动文件名
         * @param toPath    移动后目录
         * @param toName    移动后文件名
         * @return 是否移动成功
         */
        public static boolean moveFile(FtpConfig ftpConfig, String fromPath, String fromName, String toPath, String toName) {
            try {
                FTPClient ftpClient = connectClient(ftpConfig);
                boolean changeResult = ftpClient.changeWorkingDirectory(fromPath);
                if (!changeResult) {
                    throw new RuntimeException("切换目录失败");
                }
                boolean result = ftpClient.rename(fromName, toPath + File.separator + toName);
                // 退出FTP
                ftpClient.logout();
                //归还对象
                offer(ftpClient);
                return result;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    
    
        /**
         * 删除文件
         *
         * @param ftpConfig  配置
         * @param remotePath 远程目录
         * @param fileName   文件名
         * @return 是否删除成功
         */
        public static boolean deleteFile(FtpConfig ftpConfig, String remotePath, String fileName) {
            try {
                FTPClient ftpClient = connectClient(ftpConfig);
                boolean changeResult = ftpClient.changeWorkingDirectory(remotePath);
                if (!changeResult) {
                    throw new RuntimeException("切换目录失败");
                }
                boolean result = ftpClient.deleteFile(fileName);
                // 退出FTP
                ftpClient.logout();
                //归还对象
                offer(ftpClient);
                return result;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    
        /**
         * 下载文件
         *
         * @param ftpConfig  配置
         * @param remotePath 远程目录
         * @param fileName   文件名
         * @param localPath  本地目录
         * @param localName  本地文件名
         * @return 是否下载成功
         */
        public static boolean download(FtpConfig ftpConfig, String remotePath, String fileName, String localPath, String localName) {
            try {
                FTPClient ftpClient = connectClient(ftpConfig);
                boolean changeResult = ftpClient.changeWorkingDirectory(remotePath);
                if (!changeResult) {
                    throw new RuntimeException("切换目录失败");
                }
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                File file = new File(localPath, localName);
                if (!file.getParentFile().exists()) {
                    boolean mkdirsResult = file.getParentFile().mkdirs();
                    if (!mkdirsResult) {
                        throw new RuntimeException("创建目录失败");
                    }
                }
                if (!file.exists()) {
                    boolean createFileResult = file.createNewFile();
                    if (!createFileResult) {
                        throw new RuntimeException("创建文件失败");
                    }
                }
                OutputStream outputStream = new FileOutputStream(file);
                boolean result = ftpClient.retrieveFile(fileName, outputStream);
                outputStream.flush();
                outputStream.close();
                // 退出FTP
                ftpClient.logout();
                //归还对象
                offer(ftpClient);
                return result;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    
        /**
         * 上传文件
         *
         * @param ftpConfig   配置
         * @param remotePath  远程目录
         * @param inputStream 待上传文件输入流
         * @param fileName    文件名
         * @return 是否上传成功
         */
        public static boolean upload(FtpConfig ftpConfig, String remotePath, InputStream inputStream, String fileName) {
            try {
                FTPClient ftpClient = connectClient(ftpConfig);
                boolean changeResult = ftpClient.changeWorkingDirectory(remotePath);
                if (!changeResult) {
                    throw new RuntimeException("切换目录失败");
                }
                // 设置被动模式
                ftpClient.enterLocalPassiveMode();
                // 设置流上传方式
                ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
                // 设置二进制上传
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                //中文存在问题
                // 上传 fileName为上传后的文件名
                boolean result = ftpClient.storeFile(fileName, inputStream);
                // 关闭本地文件流
                inputStream.close();
                // 退出FTP
                ftpClient.logout();
                //归还对象
                offer(ftpClient);
                return result;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    
        /**
         * 登录ftp
         *
         * @param ftpConfig 配置
         * @return 是否登录成功
         * @throws IOException
         */
        private static FTPClient connectClient(FtpConfig ftpConfig) throws IOException {
            FTPClient ftpClient = getClient();
            // 连接FTP服务器
            ftpClient.connect(ftpConfig.ip, ftpConfig.port);
            // 登录FTP
            ftpClient.login(ftpConfig.userName, ftpConfig.password);
            // 正常返回230登陆成功
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                throw new RuntimeException("连接ftp失败");
            }
            ftpClient.setControlEncoding("GBK");
            return ftpClient;
        }
    
        /**
         * 获取ftpClient对象
         *
         * @return 获取client对象
         */
        private static FTPClient getClient() {
            FTPClient ftpClient = FTP_CLIENT_QUEUE.poll();
            if (ftpClient != null) {
                return ftpClient;
            }
            return new FTPClient();
        }
    
        private static void offer(FTPClient ftpClient) {
            FTP_CLIENT_QUEUE.offer(ftpClient);
        }
    
        /**
         * 连接ftp配置
         */
        public static class FtpConfig {
            private String ip;
            private int port;
            private String userName;
            private String password;
    
            public FtpConfig setIp(String ip) {
                this.ip = ip;
                return this;
            }
    
            public FtpConfig setPort(int port) {
                this.port = port;
                return this;
            }
    
            public FtpConfig setUserName(String userName) {
                this.userName = userName;
                return this;
            }
    
            public FtpConfig setPassword(String password) {
                this.password = password;
                return this;
            }
        }
    }
    
    

    使用示例

    public class Main {
        private final static Logger logger = LoggerFactory.getLogger(Main.class);
    
        public static void main(String[] args) throws Exception {
            //连接配置
            FtpUtil.FtpConfig ftpConfig = new FtpUtil.FtpConfig().setUserName("1098481123@qq.com")
                    .setPassword("zhan123456").setIp("192.168.33.105").setPort(21);
            //创建目录
            FtpUtil.makeDirectory(ftpConfig, "/", "test");
            FtpUtil.makeDirectory(ftpConfig, "/", "test2");
    
            //上传文件
            InputStream inputStream = new FileInputStream("G:\\a.txt");
            FtpUtil.upload(ftpConfig, "/test", inputStream, "zhan.txt");
    
            //下载文件
            FtpUtil.download(ftpConfig, "/test", "zhan.txt", "G:", "b.txt");
    
            //移动文件
            FtpUtil.moveFile(ftpConfig, "/test", "zhan.txt", "/test2", "zhan1.txt");
    
            //删除文件
            FtpUtil.deleteFile(ftpConfig, "/test", "zhan.txt");
            FtpUtil.deleteFile(ftpConfig, "/test2", "zhan1.txt");
        }
    }
    
    
    展开全文
  • 文件FTP上传的工具类

    2018-07-08 11:07:08
    ftp 上传时,用到的工具类,项目上配置好ftp服务器后,controller可以方便的调用此工具类进行上传
  • java版FTP工具类

    2012-09-15 23:12:12
    ftp工具类,帮助你很容易的实现ftp功能
  • FTP工具类,包括:文件夹上传下载,文件删除(包括非空文件夹),重命名等操作 基本的操作应该都有
  • 采用java实现FTP文件的上传下载,包含文件以及文件夹上传下载,新建文件夹等基本相关操作,不会出现文件名的中文乱码,内含demo相关测试以及jar包,可直接导入使用,采用MyEclipse8.5,jdk1.6亲测无问题
  • 本文基于commons-pool2的ObjectPool接口构建了ftpClientPool,并以ftpClientPool为基础构建了FTPUtil工具类。 可以实现FTPClient的复用,以减少频繁创建FTPClient对象而造成的性能开销; 可以实现线程安全的并发访问...
  • FTP和SFTP工具类(java)

    2017-12-13 10:17:04
    FTP和SFTP工具类,基于java语言 其中FTP修改默认模式为被动模式 文档还包括了需要引用的maven依赖内容
  • Java FTP工具类,结合文档 https://blog.csdn.net/qq_16946803/article/details/105215103
  • Java操作FTP工具类(实例详解)

    千次阅读 2018-09-06 10:38:00
    这里使用Apache的FTP jar 包 ... 工具类   package com.zit.ftp; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java....
  • ftp支持主动和被动模式上传下载,sftp支持上传功能
  • NULL 博文链接:https://yangmeng.iteye.com/blog/2077964
  • C# FTP 工具类

    千次阅读 2017-08-23 13:45:13
    public class FtpTool { string ftpServerIP; //ftp服务器地址 string ftpRemotePath; //ftp目录 string ftpUserID; //登录用户 string ftpPassword; //登录密码 string ftpURI; //访问资
  • ftp工具类(util)

    2014-09-20 15:16:51
    ftp文件服务器的调用、上传下载方法,If you need you can download
  • 项目中添加该工具类,用一下语句调用 FTPUtil ftpUtil = new FTPUtil("172.16.1.41",21,"admin","123456"); ftpUtil.downLoadFile("20190913.txt","D:\\ftplocal\\20190913.txt"); ftpUtil.uploadFile&#...
  • Apache FTPClient操作FTP工具类
  • ftp工具类:上传与下载文件

    千次阅读 多人点赞 2019-03-27 11:49:49
    服务器已经配置好ftp服务 linux服务器搭建ftp服务: https://program.blog.csdn.net/article/details/88825921 需要用到的jar包: <dependency> <groupId>commons-net</groupId> <artifactId...
  • ftp工具类和jar包

    2014-02-12 13:52:00
    java实现的ftp工具类以及用到的jar包,能够实现下载、上传文件,还能获取文件列表、切换目录等功能
  • 工具是方便自己开发FTP上传下载需求写的,直接拿来就可以使用,方便那些自己懒得写,或者是想借鉴开发的人用。

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 95,786
精华内容 38,314
关键字:

ftp工具类