JAVA FTP文件上传下载删除

Java Web应用中的文件一般由专门的文件服务器管理,Ftp,FastDFS,HDFS等都是不错的选择,其中Ftp由于其安装维护的简易性,是很多小型系统的首要选择,现针对Ftp的文件管理做一个java的实现。代码如下:
/**
 * 基于Java JDK1.8封装的操作Ftp服务器文件的帮助类,包含基本的上传下载和删除文件。
 * 服务器连接信息需要在sysconfig.properties配置文件里面配置连接信息
 * file_ftp_ip  ftp服务器ip信息
 * file_ftp_port  ftp服务器端口,默认
 * file_ftp_user  ftp服务器用户名,该账号具有自己根路径下文件的所有权限
 * file_ftp_pass  ftp服务器密码
 */
public class FtpHelper {
    private static ILogTracer tracer = LogTracerFactory.getInstance(FtpHelper.class);
    /**
     * 上传文件到Ftp服务器,同名文件会覆盖
     * @param fileContent 文件二进制数组
     * @param fileName 文件名
     * @param filePath 从ftp服务器根目录开始的文件保存路径
     * */
    public static void uploadFileToFtp(byte[] fileContent,String fileName,String filePath){
        uploadFileToFtp(fileContent,fileName,filePath,false);
    }

    /**
     * 上传文件到Ftp服务器,可设置同名文件是否覆盖
     * @param fileContent 文件二进制数组
     * @param fileName 文件名
     * @param filePath 从ftp服务器根目录开始的文件保存路径
     * */
    public static void uploadFileToFtp(byte[] fileContent,String fileName,String filePath,boolean isCover){
        OutputStream os = null;
        FtpClient ftpClient=null;
        try {
            ftpClient = getFtpClient();//获得FtpClient
            String[] directories = filePath.split("/");
            for(String directory:directories){//创建所需文件夹
                if(!directory.equals(""))
                {
                    try {
                        ftpClient.makeDirectory(directory);
                    }catch (FtpProtocolException e) {

                    }
                    ftpClient.changeDirectory(directory);
                }
            }
            ftpClient.changeToParentDirectory();

            os =  ftpClient.putFileStream(filePath+"/"+fileName,isCover);
            os.write(fileContent);
        }
        catch (IOException e) {
            e.printStackTrace();
        } catch (FtpProtocolException e) {
            e.printStackTrace();
        } finally {
            closeSources(os,ftpClient);
        }
    }
    /**
     * 从Ftp下载文件,
     * @param fileName 带相对路径的文件名,从根路径开始
     * */
    public static File downloadFileFromFtp(String fileName){
        InputStream is = null;
        FileOutputStream os = null;
        FtpClient ftpClient=null;
        File file_in = null;
        try
        {
            ftpClient = getFtpClient();//获得FtpClient
            // 获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。
            is = ftpClient.getFileStream(fileName);
            file_in = new File("tmp");//通过临时文件中转
            file_in.createNewFile();
            os = new FileOutputStream(file_in);

            byte[] bytes = new byte[1024];
            int c;
            while ((c = is.read(bytes)) != -1)
            {
                os.write(bytes, 0, c);
            }
        } catch (IOException ex)
        {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        } catch (FtpProtocolException e) {
            e.printStackTrace();
        } finally
        {
            closeSources(is, os, ftpClient);//ftpClient一定要最后关闭
        }
        return file_in;
    }
    /**
     * 通过文件名删除Ftp服务器上的文件
     * @param fileName 文件名,该文件名从ftp服务器根路径开始
     *                 例:"/root/sample/sample.txt"
     * */
    public static void deleteFileOnFtp(String fileName){
        FtpClient ftpClient=null;
        try {
            ftpClient = getFtpClient();//获得FtpClient
            ftpClient.deleteFile(fileName);
        } catch (FtpProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeSources(ftpClient);
        }
    }
    /**
     * 根据sysconfig.properties配置文件得到FtpClient连接
     * @return 返回已登录的FtpClient连接,通过该连接可直接像Ftp发送各种命令。
     * */
    public static FtpClient getFtpClient(){
        FtpClient ftpClient=null;
        try
        {
            String ip = SysconfigHelper.getProperty("file_ftp_ip");
            String user = SysconfigHelper.getProperty("file_ftp_user");
            String password = SysconfigHelper.getProperty("file_ftp_pass");
            ftpClient =FtpClient.create();
//          ftpClient.connect(new InetSocketAddress(ip, port));
            ftpClient = FtpClient.create(ip);
            ftpClient.login(user, password.toCharArray(), password);
            // 设置成2进制传输
            ftpClient.setBinaryType();
        } catch (IOException ex)
        {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        } catch (FtpProtocolException e) {
            e.printStackTrace();
        }
        return ftpClient;
    }
    /**
     * 关闭所有实现Closeable接口的(IO)资源
     * */
    public static void closeSources(Closeable...sources){
        if(sources.length>0)
        {
            for(Closeable source : sources)
            {
                if(source!=null){
                    try {
                        source.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    /**
     * 获得java.io.File类型的byte数组
     * */
    public static byte[] getFileByteArray(File file){
        FileInputStream fis=null;
        ByteArrayOutputStream bos=null;
        try {
            fis = new FileInputStream(file);
            bos = new ByteArrayOutputStream(1024);
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }

            return bos.toByteArray();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            closeSources(fis,bos);
        }
        return new byte[0];
    }
    /**
     * 获得MultipartFile类型的byte数组
     * */
    public static byte[] getFileByteArray(MultipartFile file){
        try {
            return file.getBytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }
    /**
     * 获得文件基于MD5的hash值
     */
    public static String getFileMd5HashCode(File file){
        InputStream fis = null;
        try {
            fis =  new FileInputStream(file);
            byte[] buffer = new byte[1024];
            MessageDigest digest = MessageDigest.getInstance("MD5");
            int numRead;
            do {
                numRead = fis.read(buffer);
                if (numRead > 0) {
                    digest.update(buffer, 0, numRead);
                }
            } while (numRead != -1);

            byte[] md5ByteArr = digest.digest();

            StringBuffer result = new StringBuffer();

            for (int i=0; i < md5ByteArr.length; i++) {
                result.append(Integer.toString((md5ByteArr[i] & 0xff) + 0x100, 16).substring(1));
            }
            return result.toString();
        } catch (FileNotFoundException e) {
            throw new Exception("文件不存在");
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("文件权限不足");
        } catch (IOException e) {
            throw new Exception("读取文件错误");
        }
        finally {
            closeSources(fis);
        }
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值