当前位置: 首页>>代码示例>>Java>>正文


Java FTPClient.isConnected方法代码示例

本文整理汇总了Java中org.apache.commons.net.ftp.FTPClient.isConnected方法的典型用法代码示例。如果您正苦于以下问题:Java FTPClient.isConnected方法的具体用法?Java FTPClient.isConnected怎么用?Java FTPClient.isConnected使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.apache.commons.net.ftp.FTPClient的用法示例。


在下文中一共展示了FTPClient.isConnected方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: download

import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
public static byte[] download(String url, int port, String username, String password, String remotePath,
		String fileName) throws IOException {
	FTPClient ftp = new FTPClient();
	ftp.setConnectTimeout(5000);
	ftp.setAutodetectUTF8(true);
	ftp.setCharset(CharsetUtil.UTF_8);
	ftp.setControlEncoding(CharsetUtil.UTF_8.name());
	try {
		ftp.connect(url, port);
		ftp.login(username, password);// 登录
		if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
			ftp.disconnect();
			throw new IOException("login fail!");
		}
		ftp.changeWorkingDirectory(remotePath);
		ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
		FTPFile[] fs = ftp.listFiles();
		for (FTPFile ff : fs) {
			if (ff.getName().equals(fileName)) {
				try (ByteArrayOutputStream is = new ByteArrayOutputStream();) {
					ftp.retrieveFile(ff.getName(), is);
					byte[] result = is.toByteArray();
					return result;
				}
			}
		}

		ftp.logout();
	} finally {
		if (ftp.isConnected()) {
			ftp.disconnect();
		}
	}
	return null;
}
 
开发者ID:HankXV,项目名称:Limitart,代码行数:36,代码来源:FTPUtil.java

示例2: uploadFile

import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
 * 上传文件至FTP服务器
 * 
 * @author gaoxianglong
 */
public boolean uploadFile(File file) {
	boolean result = false;
	FTPClient ftpClient = ftpConnManager.getFTPClient();
	if (null == ftpClient || !ftpClient.isConnected()) {
		return result;
	}
	try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file.getPath()))) {
		boolean storeFile = ftpClient.storeFile(file.getName(), in);
		if (storeFile) {
			result = true;
			log.info("file-->" + file.getPath() + "成功上传至FTP服务器");
		}
	} catch (Exception e) {
		log.error("error", e);
	} finally {
		disconnect(ftpClient);
	}
	return result;
}
 
开发者ID:yunjiweidian,项目名称:TITAN,代码行数:25,代码来源:FtpUtils.java

示例3: downloadFile

import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
 * 从FTP服务器下载指定的文件至本地
 * 
 * @author gaoxianglong
 */
public boolean downloadFile(File file) {
	boolean result = false;
	FTPClient ftpClient = ftpConnManager.getFTPClient();
	if (null == ftpClient || !ftpClient.isConnected()) {
		return result;
	}
	try (BufferedOutputStream out = new BufferedOutputStream(
			new FileOutputStream(System.getProperty("user.home") + "/" + file.getName()))) {
		result = ftpClient.retrieveFile(file.getName(), out);
		if (result) {
			result = true;
			log.info("file-->" + file.getPath() + "成功从FTP服务器下载");
		}
	} catch (Exception e) {
		log.error("error", e);
	} finally {
		disconnect(ftpClient);
	}
	return result;
}
 
开发者ID:yunjiweidian,项目名称:TITAN,代码行数:26,代码来源:FtpUtils.java

示例4: getFTPClient

import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
public FTPClient getFTPClient(Uri uri) throws SocketException, IOException, AuthenticationException{
    NetworkCredentialsDatabase database = NetworkCredentialsDatabase.getInstance();
    Credential cred = database.getCredential(uri.toString());
    if(cred==null){
        cred = new Credential("anonymous","", buildKeyFromUri(uri).toString(), true);
    }
    FTPClient ftpclient = ftpClients.get(cred);
    if (ftpclient!=null && ftpclient.isConnected()){
        return ftpclient;
    }
    // Not previous session found, open a new one
    Log.d(TAG, "create new ftp session for "+uri);
    FTPClient ftp = getNewFTPClient(uri,FTP.BINARY_FILE_TYPE);
    if(ftp==null)
        return null;
    Uri key = buildKeyFromUri(uri);
    Log.d(TAG, "new ftp session created with key "+key);
    ftpClients.put(cred, ftp);
    return ftp;
}
 
开发者ID:archos-sa,项目名称:aos-FileCoreLibrary,代码行数:21,代码来源:Session.java

示例5: getFTPSClient

import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
public FTPClient getFTPSClient(Uri uri) throws SocketException, IOException, AuthenticationException{
    NetworkCredentialsDatabase database = NetworkCredentialsDatabase.getInstance();
    Credential cred = database.getCredential(uri.toString());
    if(cred==null){
        cred = new Credential("anonymous","", buildKeyFromUri(uri).toString(), true);
    }
    FTPClient ftpclient = ftpsClients.get(cred);
    if (ftpclient!=null && ftpclient.isConnected()){
        return ftpclient;
    }
    // Not previous session found, open a new one
    Log.d(TAG, "create new ftp session for "+uri);
    FTPClient ftp = getNewFTPSClient(uri, FTP.BINARY_FILE_TYPE);
    if(ftp==null)
        return null;
    Uri key = buildKeyFromUri(uri);
    Log.d(TAG, "new ftp session created with key "+key);
    ftpsClients.put(cred, ftp);
    return ftp;
}
 
开发者ID:archos-sa,项目名称:aos-FileCoreLibrary,代码行数:21,代码来源:Session.java

示例6: closeFTPClient

import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
 * 关闭FTP连接
 * 
 * @author wangwei
 */
public void closeFTPClient(FTPClient ftp) throws Exception {

	try {
		if (ftp.isConnected())
			ftp.disconnect();
	} catch (Exception e) {
		throw new Exception("关闭FTP服务出错!");
	}
}
 
开发者ID:smxc,项目名称:garlicts,代码行数:15,代码来源:FTPUpload.java

示例7: downloadFile

import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
public static boolean downloadFile(String url, int port, String username, String password,
                                   String remotePath, String fileName, String localPath) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    try {
        int reply;
        ftp.connect(url, port);
        ftp.login(username, password);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
        }
        ftp.changeWorkingDirectory(remotePath);
        FTPFile[] fs = ftp.listFiles();
        System.out.println(fs.length);
        for (FTPFile ff : fs) {
            System.out.println(ff.getName());
            if (ff.getName().equals(fileName)) {
                File localFile = new File(localPath + "/" + ff.getName());
                OutputStream is = new FileOutputStream(localFile);
                ftp.retrieveFile(ff.getName(), is);
                is.close();
            }
        }
        ftp.logout();
        success = true;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
    return success;
}
 
开发者ID:thomas-young-2013,项目名称:wherehowsX,代码行数:40,代码来源:FtpUtils.java

示例8: disconnect

import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
 * Logout and disconnect the given FTPClient. *
 * 
 * @param client
 * @throws IOException
 */
private void disconnect(FTPClient client) throws IOException {
  if (client != null) {
    if (!client.isConnected()) {
      throw new FTPException("Client not connected");
    }
    boolean logoutSuccess = client.logout();
    client.disconnect();
    if (!logoutSuccess) {
      LOG.warn("Logout failed while disconnecting, error code - "
          + client.getReplyCode());
    }
  }
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:20,代码来源:FTPFileSystem.java

示例9: FTPInputStream

import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
public FTPInputStream(InputStream stream, FTPClient client,
    FileSystem.Statistics stats) {
  if (stream == null) {
    throw new IllegalArgumentException("Null InputStream");
  }
  if (client == null || !client.isConnected()) {
    throw new IllegalArgumentException("FTP client null or not connected");
  }
  this.wrappedStream = stream;
  this.client = client;
  this.stats = stats;
  this.pos = 0;
  this.closed = false;
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:15,代码来源:FTPInputStream.java

示例10: uploadFile

import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
 * Description: 向FTP服务器上传文件
 * @param url FTP服务器hostname
 * @param port FTP服务器端口
 * @param username FTP登录账号
 * @param password FTP登录密码
 * @param path FTP服务器保存目录
 * @param filename 上传到FTP服务器上的文件名
 * @param input 输入流
 * @return 成功返回true,否则返回false
 */
public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {
	boolean success = false;
	FTPClient ftp = new FTPClient();
	try {
		int reply;
		ftp.connect(url, port);//连接FTP服务器
		//如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
		ftp.login(username, password);//登录
		reply = ftp.getReplyCode();
		if (!FTPReply.isPositiveCompletion(reply)) {
			ftp.disconnect();
			return success;
		}
		//设置FTP以2进制传输
		ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
		//TODO 读取文件配置判断是否使用主动
		ftp.enterLocalPassiveMode();//被动
		//ftp.enterLocalActiveMode();//主动
		//创建目录
		mkDir(path,ftp);
		//改变目录
		ftp.changeWorkingDirectory(path);
		ftp.storeFile(filename, input);			
		input.close();
		ftp.logout();
		success = true;
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		if (ftp.isConnected()) {
			try {
				ftp.disconnect();
			} catch (IOException ioe) {
			}
		}
	}
	return success;
}
 
开发者ID:Xvms,项目名称:xvms,代码行数:50,代码来源:FtpClient.java

示例11: mkDir

import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
* 循环创建目录,并且创建完目录后,设置工作目录为当前创建的目录下
*/
public static boolean mkDir(String ftpPath,FTPClient ftp2) {
 if (!ftp2.isConnected()) {
  return false;
 }
 try {
  // 将路径中的斜杠统一
  char[] chars = ftpPath.toCharArray();
  StringBuffer sbStr = new StringBuffer(256);
  for (int i = 0; i < chars.length; i++) {
   if ('\\' == chars[i]) {
   	sbStr.append('/');
   }else{
   	sbStr.append(chars[i]);
   }
  }
  ftpPath = sbStr.toString();
  //System.out.println("ftpPath" + ftpPath);
  if (ftpPath.indexOf('/') == -1) {
   // 只有一层目录
   ftp2.makeDirectory(new String(ftpPath.getBytes(),"iso-8859-1"));
   ftp2.changeWorkingDirectory(new String(ftpPath.getBytes(),"iso-8859-1"));
  } else {
   // 多层目录循环创建
   String[] paths = ftpPath.split("/");
   // String pathTemp = "";
   for (int i = 0; i < paths.length; i++) {
   	ftp2.makeDirectory(new String(paths[i].getBytes(),"iso-8859-1"));
   	ftp2.changeWorkingDirectory(new String(paths[i].getBytes(), "iso-8859-1"));
   }
  }
  return true;
 } catch (Exception e) {
  e.printStackTrace();
  return false;
 }
}
 
开发者ID:Xvms,项目名称:xvms,代码行数:40,代码来源:FtpClient.java

示例12: create

import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
 * A stream obtained via this call must be closed before using other APIs of
 * this class or else the invocation will block.
 */
@Override
public FSDataOutputStream create(Path file, FsPermission permission,
    boolean overwrite, int bufferSize, short replication, long blockSize,
    Progressable progress) throws IOException {
  final FTPClient client = connect();
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  FileStatus status;
  try {
    status = getFileStatus(client, file);
  } catch (FileNotFoundException fnfe) {
    status = null;
  }
  if (status != null) {
    if (overwrite && !status.isDirectory()) {
      delete(client, file, false);
    } else {
      disconnect(client);
      throw new FileAlreadyExistsException("File already exists: " + file);
    }
  }
  
  Path parent = absolute.getParent();
  if (parent == null || !mkdirs(client, parent, FsPermission.getDirDefault())) {
    parent = (parent == null) ? new Path("/") : parent;
    disconnect(client);
    throw new IOException("create(): Mkdirs failed to create: " + parent);
  }
  client.allocate(bufferSize);
  // Change to parent directory on the server. Only then can we write to the
  // file on the server by opening up an OutputStream. As a side effect the
  // working directory on the server is changed to the parent directory of the
  // file. The FTP client connection is closed when close() is called on the
  // FSDataOutputStream.
  client.changeWorkingDirectory(parent.toUri().getPath());
  FSDataOutputStream fos = new FSDataOutputStream(client.storeFileStream(file
      .getName()), statistics) {
    @Override
    public void close() throws IOException {
      super.close();
      if (!client.isConnected()) {
        throw new FTPException("Client not connected");
      }
      boolean cmdCompleted = client.completePendingCommand();
      disconnect(client);
      if (!cmdCompleted) {
        throw new FTPException("Could not complete transfer, Reply Code - "
            + client.getReplyCode());
      }
    }
  };
  if (!FTPReply.isPositivePreliminary(client.getReplyCode())) {
    // The ftpClient is an inconsistent state. Must close the stream
    // which in turn will logout and disconnect from FTP server
    fos.close();
    throw new IOException("Unable to create file: " + file + ", Aborting");
  }
  return fos;
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:64,代码来源:FTPFileSystem.java

示例13: execute

import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
 * 执行FTP回调操作的方法
 *
 * @param <T>      the type parameter
 * @param callback 回调的函数
 * @return the t
 * @throws IOException the io exception
 */
public <T> T execute(FTPClientCallback<T> callback) throws IOException {
    FTPClient ftp = new FTPClient();
    try {
        //登录FTP服务器
        try {
            //设置超时时间
            ftp.setDataTimeout(7200);
            //设置默认编码
            ftp.setControlEncoding(DEAFULT_REMOTE_CHARSET);
            //设置默认端口
            ftp.setDefaultPort(DEAFULT_REMOTE_PORT);
            //设置是否显示隐藏文件
            ftp.setListHiddenFiles(false);
            //连接ftp服务器
            if (StringUtils.isNotEmpty(port) && NumberUtils.isDigits(port)) {
                ftp.connect(host, Integer.valueOf(port));
            } else {
                ftp.connect(host);
            }
        } catch (ConnectException e) {
            logger.error("连接FTP服务器失败:" + ftp.getReplyString() + ftp.getReplyCode());
            throw new IOException("Problem connecting the FTP-server fail", e);
        }
        //得到连接的返回编码
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
        }
        //登录失败权限验证失败
        if (!ftp.login(getUsername(), getPassword())) {
            ftp.quit();
            ftp.disconnect();
            logger.error("连接FTP服务器用户或者密码失败::" + ftp.getReplyString());
            throw new IOException("Cant Authentificate to FTP-Server");
        }
        if (logger.isDebugEnabled()) {
            logger.info("成功登录FTP服务器:" + host + " 端口:" + port);
        }
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        //回调FTP的操作
        return callback.doTransfer(ftp);
    } finally {
        //FTP退出
        ftp.logout();
        //断开FTP连接
        if (ftp.isConnected()) {
            ftp.disconnect();
        }
    }
}
 
开发者ID:numsg,项目名称:spring-boot-seed,代码行数:60,代码来源:FTPClientImpl.java

示例14: disconnect

import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
 * 断开与远程服务器的连接
 *
 * @throws IOException
 */
public void disconnect(FTPClient ftpClient) throws IOException {
    if (ftpClient.isConnected()) {
        ftpClient.disconnect();
    }
}
 
开发者ID:numsg,项目名称:spring-boot-seed,代码行数:11,代码来源:FtpHelper.java


注:本文中的org.apache.commons.net.ftp.FTPClient.isConnected方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。