`
747017186
  • 浏览: 317602 次
社区版块
存档分类
最新评论

FTP 上传下载

    博客分类:
  • java
 
阅读更多

java实现ftp的上传和下载,用的是Apache下的net包。直接看例子:

/**
 * Mainbo.com Inc.
 * Copyright (c) 2015-2017 All Rights Reserved.
 */
package com.mainbo.jy.resdown.Main;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;

/**
 * <pre>
 *
 * </pre>
 *
 * @author huangjunhua
 * @version $Id: FtpMain.java, v 1.0 2015年5月15日 上午10:57:52 huangjunhua Exp $
 */
public class FtpMain {
	public static void main(String[] args) {
//		testUpload();
		testDownload();
	}
	
	 /** 
     * FTP上传单个文件测试 
     */ 
    public static void testUpload() { 
        FTPClient ftpClient = new FTPClient(); 
        FileInputStream fis = null; 

        try { 
            ftpClient.connect("172.16.7.78"); //FTP下载地址
            ftpClient.login("huangjunhua", "123456"); //登陆

            File srcFile = new File("D:\\a.xml"); //选择要上传的文件
            fis = new FileInputStream(srcFile); 
            //设置上传目录 
            ftpClient.changeWorkingDirectory("/a/b"); //选择上传的路径
            ftpClient.setBufferSize(1024); 
            ftpClient.setControlEncoding("UTF-8"); 
            //设置文件类型(二进制) 
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); 
            ftpClient.storeFile("3.xml", fis); //保存的ftp服务器上的文件名,上传ftp
        } catch (IOException e) { 
            e.printStackTrace(); 
            throw new RuntimeException("FTP客户端出错!", e); 
        } finally { 
            IOUtils.closeQuietly(fis); 
            try { 
                ftpClient.disconnect(); 
            } catch (IOException e) { 
                e.printStackTrace(); 
                throw new RuntimeException("关闭FTP连接发生异常!", e); 
            } 
        } 
    }
    
    /** 
     * FTP下载单个文件测试 
     */ 
    public static void testDownload() { 
        FTPClient ftpClient = new FTPClient(); 
        FileOutputStream fos = null; 

        try { 
            ftpClient.connect("172.16.7.78"); 
            ftpClient.login("huangjunhua", "123456"); 

            String remoteFileName = "/a/b/3.xml"; //选择ftp上的文件
            fos = new FileOutputStream("D:\\P.xml"); //下载到本地的文件的名字

            ftpClient.setBufferSize(1024); 
            //设置文件类型(二进制) 
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); 
            ftpClient.retrieveFile(remoteFileName, fos); //从ftp上下载到本地
        } catch (IOException e) { 
            e.printStackTrace(); 
            throw new RuntimeException("FTP客户端出错!", e); 
        } finally { 
            IOUtils.closeQuietly(fos); 
            try { 
                ftpClient.disconnect(); 
            } catch (IOException e) { 
                e.printStackTrace(); 
                throw new RuntimeException("关闭FTP连接发生异常!", e); 
            } 
        } 
    } 
}

 很简单的,直接调用。嘿嘿...

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics