FTP文件操作

JAVA使用FTP远程管理文件

用到的JAR包

点击下载commons-net-3.6.jar

核心类 FTPClient
package com.shuaihui.txtread.tools;
/**
* 作    者: 糖葫芦太甜
* 时    间: 2019年4月25日下午6:16:09
* 文件名: Test1.java
**/
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;


@SuppressWarnings({"resource"})
public class FTPClientUser {
	
	//FTP客户端对象
    private static FTPClient ftp;
    //需要连接到的ftp端的host
    private String host = "192.168.2.130";
    //连接端口,默认21
    private int port = 21;
    //要连接到的ftp端的名字
    private String name = "test";
    //要连接到的ftp端的对应得密码
    private String pwd = "123456";
    
    /**
     * 创建FTP链接
     * 使用默认的参数创建FTP链接
     */
	public FTPClientUser() {
		ftp = initFTP();
	}
	
	/**
	 * 全参数的构造方法  在生成类的同时建立FTP链接
	 * @param host FTP服务器的IP地址
	 * @param port FTP服务器开放的端口
	 * @param name FTP服务器的登陆用户名
	 * @param pwd  FTP服务器的登陆密码
	 */
	public FTPClientUser(String host, int port, String name, String pwd) {
		ftp = initFTP();
		this.host = host;
		this.port = port;
		this.name = name;
		this.pwd = pwd;
	}
	
	/**
	 * 初始化FTP链接
	 * @return 返回FTP链接 
	 */
	public FTPClient initFTP(){
		ftp = new FTPClient();
		try {
			//创建ftp链接
			ftp.connect(host, port);
			//登录ftp,使用用戶名和密碼
			ftp.login(name,pwd);
		} catch (SocketException e) {
			System.out.println("网络链接失败!"+e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("链接创建失败"+e.getMessage());
			e.printStackTrace();
		}
		return ftp;
	}
	
	/**
	 * 关闭FTP链接
	 */
	public void closeFTP(){
		try {
			ftp.logout();
		} catch (IOException e) {
			System.out.println("退出账号时出现异常!"+e.getMessage());
			e.printStackTrace();
		}
	}
	
	/**
	 * 上传文件 路径方式
	 * @param localFilePath  本地文件所在目录
	 * @param uploadFilePath 上传的文件目录
	 * @param fileName		   上传的文件名字
	 */
	public void sendFiletoFTP(String localFilePath, String uploadFilePath, String fileName){
		try {
	        //读取本地文件
	        FileInputStream inputStream = new FileInputStream(new File(localFilePath));
//	        FileInputStream inputStream = new FileInputStream(new File("D:/UserExcels.xls"));
	        //设置为被动模式(如上传文件夹成功,不能上传文件,注释这行,否则报错refused:connect  )
	        ftp.enterLocalPassiveMode();
	        //设置上传路径
	        ftp.changeWorkingDirectory(uploadFilePath);
//	        ftp.changeWorkingDirectory("/");
	        //修改上传文件格式
	        ftp.setFileType(FTP.BINARY_FILE_TYPE);
	        System.out.println("修改上传文件格式完成");
	        //上传文件
	        ftp.storeFile(fileName, inputStream);
//	        ftp.storeFile("UserExcels.xls", inputStream);
	        System.out.println("上传文件完成");
	    } catch (Exception e) {
	        e.printStackTrace();
	        System.out.println("链接失败"+e.getMessage());
	    }
	}
    
	
	/**
	 * 上传文件以流的方式上传文件
	 * @param inputStream    文件流
	 * @param uploadFilePath 上传的目录
	 * @param fileName		   上传的文件名
	 */
	public void sendFiletoFTP(BufferedInputStream fileInputStream, String uploadFilePath, String fileName){
		try {
	        //读取本地文件
//	        FileInputStream inputStream = new FileInputStream(new File("D:/UserExcels.xls"));
	        //设置为被动模式(如上传文件夹成功,不能上传文件,注释这行,否则报错refused:connect  )
	        ftp.enterLocalPassiveMode();
	        //设置上传路径
	        ftp.changeWorkingDirectory(uploadFilePath);
//	        ftp.changeWorkingDirectory("/");
	        //修改上传文件格式
	        ftp.setFileType(FTP.BINARY_FILE_TYPE);
	        System.out.println("修改上传文件格式完成");
	        //上传文件
	        ftp.storeFile(fileName, fileInputStream);
//	        ftp.storeFile("UserExcels.xls", inputStream);
	        //关闭文件流
	        fileInputStream.close();
	        System.out.println("上传文件完成");
	    } catch (Exception e) {
	        e.printStackTrace();
	        System.out.println("链接失败"+e.getMessage());
	    }
	}
	
	
	
	/**
	 * 下载文件,优化传输速度
	 * @param downloadFilePath 欲下载的文件所在目录及文件名(全路径加文件名)
	 * @param localFilePath    保存到目标目录
	 */
    public void downFile(String downloadFilePath, String localFilePath) {
        try {
            InputStream is = ftp.retrieveFileStream(downloadFilePath);
            System.out.println("读取FTP文件成功");
			FileOutputStream fos = new FileOutputStream(new File(localFilePath));

            byte[] b = new byte[1024];
            int len = 0;
            while ((len = is.read(b)) != -1) {
                fos.write(b,0,len);
            }
            System.out.println("写出成功");
        } catch (IOException e) {
        	System.out.println("下载时出现问题!"+e.getMessage());
            e.printStackTrace();
        }
    }
    
    
    
    /**
     * 获取ftp某一文件(路径)下的文件名字,用于查看文件列表
     * @param Path 目录路径
     */
    public FTPFile[] getFilesName(String Path) {
        try {
            FTPFile[] files = ftp.listFiles(Path);
            for (int i = 0; i < files.length; i++) {
                System.out.println(files[i].getName());
            }
            return files; 
        } catch (IOException e) {
        	System.out.println("未获取到FTP文件目录"+e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
    
    
    
    /**
     * 删除文件至FTP通用方法  
     * @param FilePath 欲删除文件所在目录
     * @param FileName 欲删除文件名字
     */
    public void deleteFileFtp(String FilePath, String FileName){  
        try {  
            ftp.cwd(FilePath);  
            try {  
                ftp.deleteFile(FileName);
            } catch (Exception e) {  
                System.out.println("删除文件失败! 请检查系统FTP设置,并确认FTP服务启动"+e.getMessage());  
            }  
        } catch (Exception e) {  
            System.out.println("删除文件失败!"+e.getMessage());  
        }  
    }
    
    
    
    
    public void moveFile(String FileName, String TOFileName){
    	try {
			ftp.rename(FileName, TOFileName);
			System.out.println("文件移动完成");
		} catch (IOException e) {
			System.out.println("文件移动失败!"+e.getMessage());
			e.printStackTrace();
		}
    }
    
    
    
	public static void main(String[] args) {
		FTPClientUser ttpcu = new FTPClientUser();
		//发送文件到FTP服务器
		ttpcu.sendFiletoFTP("D://UserExcels.xls", "/", "UserExcels.xls");
		//相当于CentOS的mv 命令 也可用来重命名
		ttpcu.moveFile("/UserExcels.xls", "/move/UserExcels.xls");
		//删除文件
		ttpcu.deleteFileFtp("/move", "UserExcels.xls");
		//关闭链接
		ttpcu.closeFTP();
	}
}

public static void main(String[] args) {
		FTPClientUser ftp = new FTPClientUser();
        //发送文件方法
        ftp.sendFiletoFTP("/test.xls", "/", "test.xls");
        //关闭FTP服务器链接
        ftp.closeFTP();
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值