java:FTP上传文件

public class FtpUpload {
    private FTPClient client;
    /**
     * 连接FTP服务器并改变选程FTP服务器路径
     * 
     */
    public void connect(FtpConfig config) throws SocketException, IOException {
        client = new FTPClient();
        client.connect(config.getServer(), config.getPort());//设置ftp服务器地址和端口
        client.login(config.getUserName(), config.getPassword());//设置服务器用户和密码
        int reply = client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply))
            client.disconnect();
        client.changeWorkingDirectory(config.getRemotePath());
        client.setFileTransferMode(FTP.BINARY_FILE_TYPE);
        client.setFileType(FTP.BINARY_FILE_TYPE);
    }
    /**
    *关闭连接
    */
    public void closeConnect() {
        try {
            this.client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    
    /**
      *改变ftp的工作dir
      */
    public void changeDirector(String path) throws Exception {
        String pathTree[] = path.split("\\"+File.separator);
        for (int i = 0; i < pathTree.length; i++) {
            if (StringUtil.noNullBlank(pathTree[i])) {
                 if (!client.changeWorkingDirectory(pathTree[i])) {
                     client.makeDirectory(pathTree[i]);
                     client.changeWorkingDirectory(pathTree[i]);
                 }
             }
        }
    }
    /**
     * 上传指定文件或目录到服务器
     */
    public void upFile(File file) throws Exception {
        if (file.isDirectory()) {
            client.makeDirectory(file.getName());
            client.changeWorkingDirectory(file.getName());
            File[] files = file.listFiles();
            for (File row : files)
                upFile(row);
            } else {
            File inFile = new File(file.getPath());
            FileInputStream input = new FileInputStream(inFile);
            client.storeFile(new String(inFile.getName().getBytes("GBK"),"iso-8859-1"), input);
            input.close();
        }
    }
}

本文出自 “job” 博客,转载请与作者联系!

你可能感兴趣的:(FTP服务器)