上传文件到ftp(apach方法)

来源:互联网 发布:淘宝旧版本5.2.8下载 编辑:程序博客网 时间:2024/04/28 23:05
public class FTPConnectorBK {
    private String ipAddress;
    private int ipPort;
    private String userName;
    private String PassWord;
     /**
     * 构造函数
     *  @param  ip String 机器IP
     *  @param  port String 机器FTP端口号
     *  @param  username String FTP用户名
     *  @param  password String FTP密码
     *  @throws  Exception
     */
    public FTPConnectorBK(String ip, int port, String username, String password)
            throws Exception {
        ipAddress = new String(ip);
        ipPort = port;
        userName = new String(username);
        PassWord = new String(password);
    }

    /**
     * Description: 向FTP服务器上传文件
     * @param path 本地文件路径
     * @param filename 上传到FTP服务器上的文件名
     * @return 成功返回true,否则返回false
     */
    public boolean uploadFile(String path, String filename) {
        boolean returnValue = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(ipAddress, ipPort);// 连接FTP服务器
            ftp.login(userName, PassWord);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return returnValue;
            }
            InputStream ftpIn = new FileInputStream(path);
            ftp.enterLocalPassiveMode();    //没有这个 ftp.storeFile(filename, ftpIn)返回false
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);     //没有这个上传文件大小会变化

            ftp.storeFile(filename, ftpIn);
            ftpIn.close();
            ftp.logout();
            returnValue = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
        return returnValue;
    }

    public static void main(String[] args){
        try {
            new FTPConnectorBK("*********", 21, "*****", "********").uploadFile(
                    "D:\\pps_update_xml\\ppstreamsetup_update.exe", "test.exe");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
原创粉丝点击