Java Code Examples for org.apache.commons.net.ftp.ftpclient#setControlEncoding()

The following examples show how to use org.apache.commons.net.ftp.ftpclient#setControlEncoding() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FtpConnection.java    From xian with Apache License 2.0 6 votes vote down vote up
FTPClient connect(String path, String addr, int port, String username, String password) throws Exception {
    FTPClient ftp = new FTPClient();
    int reply;
    ftp.connect(addr, port);
    ftp.login(username, password);
    ftp.configure(new FTPClientConfig(ftp.getSystemType()));
    ftp.setControlEncoding("UTF-8");
    ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
    reply = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        return null;
    }
    ftp.changeWorkingDirectory(path);
    return ftp;
}
 
Example 2
Source File: FTPClientFactory.java    From hsweb-framework with Apache License 2.0 6 votes vote down vote up
public PooledObject<FTPClient> makeObject() throws Exception {
    FTPClient ftpClient = new FTPClient();
    ftpClient.setConnectTimeout(config.getClientTimeout());
    ftpClient.connect(config.getHost(), config.getPort());
    int reply = ftpClient.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        ftpClient.disconnect();
        logger.warn("FTPServer refused connection");
        return null;
    }
    boolean result = ftpClient.login(config.getUsername(), config.getPassword());
    if (!result) {
        throw new ConnectException("ftp登陆失败:" + config.getUsername() + "/password:" + config.getPassword() + "@" + config.getHost());
    }
    ftpClient.setFileType(config.getTransferFileType());
    ftpClient.setBufferSize(1024);
    ftpClient.setControlEncoding(config.getEncoding());
    if (config.isPassiveMode()) {
        ftpClient.enterLocalPassiveMode();
    }
    return new DefaultPooledObject<>(ftpClient);

}
 
Example 3
Source File: Ftp.java    From Lottery with GNU General Public License v2.0 6 votes vote down vote up
private FTPClient getClient() throws SocketException, IOException {
	FTPClient ftp = new FTPClient();
	ftp.addProtocolCommandListener(new PrintCommandListener(
			new PrintWriter(System.out)));
	ftp.setDefaultPort(getPort());
	ftp.connect(getIp());
	int reply = ftp.getReplyCode();
	if (!FTPReply.isPositiveCompletion(reply)) {
		log.warn("FTP server refused connection: {}", getIp());
		ftp.disconnect();
		return null;
	}
	if (!ftp.login(getUsername(), getPassword())) {
		log.warn("FTP server refused login: {}, user: {}", getIp(),
				getUsername());
		ftp.logout();
		ftp.disconnect();
		return null;
	}
	ftp.setControlEncoding(getEncoding());
	ftp.setFileType(FTP.BINARY_FILE_TYPE);
	ftp.enterLocalPassiveMode();
	return ftp;
}
 
Example 4
Source File: FTPUtil.java    From MeetingFilm with Apache License 2.0 5 votes vote down vote up
private void initFTPClient(){
    try{
        ftpClient = new FTPClient();
        ftpClient.setControlEncoding("utf-8");
        ftpClient.connect(hostName,port);
        ftpClient.login(userName,password);
    }catch (Exception e){
        log.error("初始化FTP失败",e);
    }
}
 
Example 5
Source File: FTPUtil.java    From MeetingFilm with Apache License 2.0 5 votes vote down vote up
private void initFTPClient(){
    try{
        ftpClient = new FTPClient();
        ftpClient.setControlEncoding("utf-8");
        ftpClient.connect(hostName,port);
        ftpClient.login(userName,password);
    }catch (Exception e){
        log.error("初始化FTP失败",e);
    }
}
 
Example 6
Source File: FTPUtil.java    From anyline with Apache License 2.0 5 votes vote down vote up
public FTPUtil(String host, String account, String password, int port){ 
      client = new FTPClient();   
  	this.host = host; 
  	this.account = account; 
  	this.password = password; 
  	this.port = port; 
      client.setControlEncoding("UTF-8");  
connect(); 
  }
 
Example 7
Source File: FTPUtil.java    From anyline with Apache License 2.0 5 votes vote down vote up
public FTPUtil(String host, String account, String password){ 
      client = new FTPClient();   
  	this.host = host; 
  	this.account = account; 
  	this.password = password; 
      client.setControlEncoding("UTF-8");   
connect(); 
  }
 
Example 8
Source File: FTPClientTemplate.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/** 
 * 返回一个FTPClient实例 
 *  
 * @throws Exception
 */  
private FTPClient getFTPClient()throws Exception {
    if (ftpClientThreadLocal.get() != null && ftpClientThreadLocal.get().isConnected()) {  
        return ftpClientThreadLocal.get();  
    } else {  
        FTPClient ftpClient = new FTPClient(); //构造一个FtpClient实例
        ftpClient.setControlEncoding(encoding); //设置字符集  
  
        connect(ftpClient); //连接到ftp服务器  
  
        //设置为passive模式  
        if (passiveMode) {  
            ftpClient.enterLocalPassiveMode();  
            String replystr=ftpClient.getReplyString();
            ftpClient.sendCommand("PASV");
            replystr=ftpClient.getReplyString();
        }  
        setFileType(ftpClient); //设置文件传输类型  
  
        try {  
            ftpClient.setSoTimeout(clientTimeout);  
            ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
        } catch (SocketException e) {
            throw new Exception("Set timeout error.", e);
        }  
        ftpClientThreadLocal.set(ftpClient);  
        return ftpClient;  
    }  
}
 
Example 9
Source File: FtpUtils.java    From kkFileView with Apache License 2.0 5 votes vote down vote up
public static FTPClient connect(String host, int port, String username, String password, String controlEncoding) throws IOException {
    FTPClient ftpClient = new FTPClient();
    ftpClient.connect(host, port);
    if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
        ftpClient.login(username, password);
    }
    int reply = ftpClient.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        ftpClient.disconnect();
    }
    ftpClient.setControlEncoding(controlEncoding);
    ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
    return ftpClient;
}
 
Example 10
Source File: FtpClientManager.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public void init() {
	if(initialized){
		return ;
	}
	
	FTPClient ftpClient = new FTPClient();
	ftpClient.setControlEncoding(ftpConfig.getEncoding());
	ftpClient.setBufferSize(ftpConfig.getBufferSize());
	ftpClient.setPassiveNatWorkaround(ftpConfig.isPasv());
	
	this.ftpClient = ftpClient;
	this.initialized = true;
}
 
Example 11
Source File: FTPUtil.java    From anyline with Apache License 2.0 4 votes vote down vote up
public FTPUtil() {   
    client = new FTPClient();   
    client.setControlEncoding("UTF-8");  
}
 
Example 12
Source File: DownloadFileFromFtpToTable.java    From MicroCommunity with Apache License 2.0 4 votes vote down vote up
/**
 * 下载文件并且存至tfs文件系统
 * 
 * @param remoteFileNameTmp
 * @param
 * @return
 */
private Map downLoadFileToTable(String remoteFileNameTmp, FTPClientTemplate ftpClientTemplate, Map ftpItemConfigInfo) {
	Map resultInfo = new HashMap();
	String tfsReturnFileName = null;
	long block = 10 * 1024;// 默认
	if (ftpClientTemplate == null) {
		resultInfo.put("SAVE_FILE_FLAG", "E");
		return resultInfo;
	}
	String localPathName = ftpItemConfigInfo.get("localPath").toString().endsWith("/") ? ftpItemConfigInfo.get("localPath").toString()
			+ ftpItemConfigInfo.get("newFileName").toString() : ftpItemConfigInfo.get("localPath").toString() + "/" + ftpItemConfigInfo.get("newFileName").toString();
	ftpItemConfigInfo.put("localfilename", localPathName);// 本地带路径的文件名回写,后面读文件时使用
	try {
		File file = new File(localPathName);
		RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");// 建立随机访问
		FTPClient ftpClient = new FTPClient();
		ftpClient.connect(ftpClientTemplate.getHost(), ftpClientTemplate.getPort());
		if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
			if (!ftpClient.login(ftpClientTemplate.getUsername(), ftpClientTemplate.getPassword())) {
				resultInfo.put("SAVE_FILE_FLAG", "E");
				resultInfo.put("remark", "登录失败,用户名【" + ftpClientTemplate.getUsername() + "】密码【" + ftpClientTemplate.getPassword() + "】");
				return resultInfo;
			}
		}
		ftpClient.setControlEncoding("UTF-8");
		ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 二进制
		ftpClient.enterLocalPassiveMode(); // 被动模式
		ftpClient.sendCommand("PASV");
		ftpClient.sendCommand("SIZE " + remoteFileNameTmp + "\r\n");
		String replystr = ftpClient.getReplyString();
		String[] replystrL = replystr.split(" ");
		long filelen = 0;
		if (Integer.valueOf(replystrL[0]) == 213) {
			filelen = Long.valueOf(replystrL[1].trim());
		} else {
			resultInfo.put("SAVE_FILE_FLAG", "E");
			resultInfo.put("remark", "无法获取要下载的文件的大小!");
			return resultInfo;
		}
		accessFile.setLength(filelen);
		accessFile.close();
		ftpClient.disconnect();

		int tnum = Integer.valueOf(ftpItemConfigInfo.get("TNUM").toString());
		block = (filelen + tnum - 1) / tnum;// 每个线程下载的快大小
		ThreadPoolExecutor cachedThreadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
		List<Future<Map>> threadR = new ArrayList<Future<Map>>();
		for (int i = 0; i < tnum; i++) {
			logger.debug("发起线程:" + i);
			// 保存线程日志
			ftpItemConfigInfo.put("threadrunstate", "R");
			ftpItemConfigInfo.put("remark", "开始下载文件");
			ftpItemConfigInfo.put("data", "文件名:" + remoteFileNameTmp);
			long start = i * block;
			long end = (i + 1) * block - 1;
			ftpItemConfigInfo.put("begin", start);
			ftpItemConfigInfo.put("end", end);
			saveTaskLogDetail(ftpItemConfigInfo);
			Map para = new HashMap();
			para.putAll(ftpItemConfigInfo);
			para.put("serverfilename", remoteFileNameTmp);
			para.put("filelength", filelen);
			para.put("tnum", i + 0);
			para.put("threadDownSize", block);
			para.put("transferflag", FTPClientTemplate.TransferType.download);
			FTPClientTemplate dumpThread = new FTPClientTemplate(para);
			Future<Map> runresult = cachedThreadPool.submit(dumpThread);
			threadR.add(runresult);
		}

		do {
			// 等待下载完成
			Thread.sleep(1000);
		} while (cachedThreadPool.getCompletedTaskCount() < threadR.size());

		saveDownFileData(ftpItemConfigInfo);
		// 下载已经完成,多线程保存数据至表中

	} catch (Exception e) {
		// TODO Auto-generated catch block
		logger.error("保存文件失败:", e);
		resultInfo.put("SAVE_FILE_FLAG", "E");
		resultInfo.put("remark", "保存文件失败:" + e);
		return resultInfo;
	}
	resultInfo.put("SAVE_FILE_FLAG", "S");
	return resultInfo;

}
 
Example 13
Source File: FTPUtil.java    From imageServer with Apache License 2.0 4 votes vote down vote up
/**
 * 获取FTP连接对象
 * @param ftpConnectAttr
 * FTP的连接配置
 * @return
 * 获取异常失败则返回null
 */
public static FTPClient getFTPClient(FTPConnectAttr ftpConnectAttr){
    if(ftpConnectAttr == null){
        log.error("FTP的连接配置不能为Null");
        return null;
    }
    if(ObjectUtil.isNull(ftpConnectAttr.address) || ObjectUtil.isNull(ftpConnectAttr.userName)){
        log.error("连接地址或连接的用户名不能为空");
        return null;
    }
    FTPClient ftpClient = new FTPClient();
    try {
        String url = ftpConnectAttr.address;
        log.info("设置ftp地址:" + url);
        if(url.split(":").length == 2){
            String[] us = url.split(":");
            int port = Integer.valueOf(us[1]);
            ftpClient.connect(us[0],port);
        }else {
            ftpClient.connect(url);
        }
        ftpClient.setDataTimeout(120000);       //设置传输超时时间为120秒
        ftpClient.setConnectTimeout(120000);       //连接超时为120秒
        ftpClient.setControlEncoding("GBK");
        log.info("设置登陆账号:" + ftpConnectAttr.userName + ":" + ftpConnectAttr.password);
        ftpClient.login(ftpConnectAttr.userName, ftpConnectAttr.password);
        int reply = ftpClient.getReplyCode();
        if(String.valueOf(reply).indexOf("2") != 0){
            log.error("ftp连接失败,返回值:" + reply);
            if(ftpClient.isConnected()){
                ftpClient.disconnect();
                return null;
            }
        }
        log.info("ftp连接成功,返回值:" + reply);
    } catch (IOException e) {
        log.error("获取FTPClient发生错误,返回null",e);
        if(ftpClient.isConnected()){
            try {
                ftpClient.disconnect();
            } catch (IOException ignored) {
            }
        }
        return null;
    }
    return ftpClient;
}