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


Java FTPClient类代码示例

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


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

示例1: download

import org.apache.commons.net.ftp.FTPClient; //导入依赖的package包/类
/**
 * 下载文件
 *
 * @param remoteDir      远程操作目录
 * @param remoteFileName 远程下载文件名
 * @param downloadFile   下载文件
 * @return 下载结果<br> true - 下载成功<br>
 * false - 下载失败
 */
public boolean download(String remoteDir, String remoteFileName, File downloadFile) {
    FTPClient ftp = null;
    try {
        ftp = initFtpClient(remoteDir);
        if (ftp == null) {
            logger.debug("ftp初始化失败");
            return false;
        }
        try (OutputStream os = new FileOutputStream(downloadFile)) {
            boolean storeRet = ftp.retrieveFile(remoteFileName, os);
            if (!storeRet) {
                logger.debug("下载文件失败");
                return false;
            }
        }
        return true;
    } catch (IOException e) {
        logger.error("FTP操作异常", e);
        return false;
    } finally {
        close(ftp);
    }
}
 
开发者ID:wyp0596,项目名称:elegant-springboot,代码行数:33,代码来源:MyFtpClient.java

示例2: 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

示例3: mkdirs

import org.apache.commons.net.ftp.FTPClient; //导入依赖的package包/类
/**
 * Convenience method, so that we don't open a new connection when using this
 * method from within another method. Otherwise every API invocation incurs
 * the overhead of opening/closing a TCP connection.
 */
private boolean mkdirs(FTPClient client, Path file, FsPermission permission)
    throws IOException {
  boolean created = true;
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  String pathName = absolute.getName();
  if (!exists(client, absolute)) {
    Path parent = absolute.getParent();
    created = (parent == null || mkdirs(client, parent, FsPermission
        .getDirDefault()));
    if (created) {
      String parentDir = parent.toUri().getPath();
      client.changeWorkingDirectory(parentDir);
      created = created && client.makeDirectory(pathName);
    }
  } else if (isFile(client, absolute)) {
    throw new ParentNotDirectoryException(String.format(
        "Can't make directory for path %s since it is a file.", absolute));
  }
  return created;
}
 
开发者ID:naver,项目名称:hadoop,代码行数:27,代码来源:FTPFileSystem.java

示例4: 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

示例5: 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

示例6: initFtpClient

import org.apache.commons.net.ftp.FTPClient; //导入依赖的package包/类
private FTPClient initFtpClient(String remoteDir) throws IOException {
    FTPClient ftp = new FTPClient();
    // 设置连接超时时间
    ftp.setConnectTimeout(CONNECT_TIMEOUT);
    // 设置传输文件名编码方式
    ftp.setControlEncoding(CONTROL_ENCODING);
    ftp.connect(host, ftpPort);
    int reply = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        logger.debug("无法连接FTP");
        return null;
    }
    boolean loginRet = ftp.login(ftpUsername, ftpPassword);
    if (!loginRet) {
        logger.debug("FTP登录失败");
        return null;
    }
    // 进入被动模式
    ftp.enterLocalPassiveMode();
    boolean changeDirResult = MKDAndCWD(ftp, remoteDir);
    if (!changeDirResult) {
        logger.debug("创建/切换文件夹失败");
        return null;
    }
    // 传输二进制文件
    ftp.setFileType(FTP.BINARY_FILE_TYPE);
    return ftp;
}
 
开发者ID:wyp0596,项目名称:elegant-springboot,代码行数:29,代码来源:MyFtpClient.java

示例7: deleteFile

import org.apache.commons.net.ftp.FTPClient; //导入依赖的package包/类
/**
 * 删除文件
 * 
 * @author wangwei
 */
public Map<String,String> deleteFile(String filename, String remoteFolder)
		throws Exception {

	Map<String,String> rs = new HashMap<String, String>();
	// 连接FTP服务器
	FTPClient ftp = this.connectFTPServer();

	try {

		// 改变当前路径到指定路径
		this.changeDirectory(remoteFolder);
		boolean result = ftp.deleteFile(filename);
		if (!result) {
			throw new Exception("FTP删除文件失败!");
		}else{
			rs.put("ret", "success");
		}

	} catch (Exception e) {
		throw e;
	}
	
	return rs;

}
 
开发者ID:smxc,项目名称:garlicts,代码行数:31,代码来源:FTPUpload.java

示例8: open

import org.apache.commons.net.ftp.FTPClient; //导入依赖的package包/类
@Override
public FSDataInputStream open(Path file, int bufferSize) throws IOException {
  FTPClient client = connect();
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  FileStatus fileStat = getFileStatus(client, absolute);
  if (fileStat.isDirectory()) {
    disconnect(client);
    throw new FileNotFoundException("Path " + file + " is a directory.");
  }
  client.allocate(bufferSize);
  Path parent = absolute.getParent();
  // Change to parent directory on the
  // server. Only then can we read the
  // file
  // on the server by opening up an InputStream. 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
  // FSDataInputStream.
  client.changeWorkingDirectory(parent.toUri().getPath());
  InputStream is = client.retrieveFileStream(file.getName());
  FSDataInputStream fis = new FSDataInputStream(new FTPInputStream(is,
      client, statistics));
  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
    fis.close();
    throw new IOException("Unable to open file: " + file + ", Aborting");
  }
  return fis;
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:32,代码来源:FTPFileSystem.java

示例9: getFileStatus

import org.apache.commons.net.ftp.FTPClient; //导入依赖的package包/类
/**
 * Convenience method, so that we don't open a new connection when using this
 * method from within another method. Otherwise every API invocation incurs
 * the overhead of opening/closing a TCP connection.
 */
private FileStatus getFileStatus(FTPClient client, Path file)
    throws IOException {
  FileStatus fileStat = null;
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  Path parentPath = absolute.getParent();
  if (parentPath == null) { // root dir
    long length = -1; // Length of root dir on server not known
    boolean isDir = true;
    int blockReplication = 1;
    long blockSize = DEFAULT_BLOCK_SIZE; // Block Size not known.
    long modTime = -1; // Modification time of root dir not known.
    Path root = new Path("/");
    return new FileStatus(length, isDir, blockReplication, blockSize,
        modTime, root.makeQualified(this));
  }
  String pathName = parentPath.toUri().getPath();
  FTPFile[] ftpFiles = client.listFiles(pathName);
  if (ftpFiles != null) {
    for (FTPFile ftpFile : ftpFiles) {
      if (ftpFile.getName().equals(file.getName())) { // file found in dir
        fileStat = getFileStatus(ftpFile, parentPath);
        break;
      }
    }
    if (fileStat == null) {
      throw new FileNotFoundException("File " + file + " does not exist.");
    }
  } else {
    throw new FileNotFoundException("File " + file + " does not exist.");
  }
  return fileStat;
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:39,代码来源:FTPFileSystem.java

示例10: 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

示例11: 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

示例12: MKDAndCWD

import org.apache.commons.net.ftp.FTPClient; //导入依赖的package包/类
private boolean MKDAndCWD(FTPClient ftp, String remoteDir) throws IOException {
    // 切分出所有子文件夹,按顺序
    String[] dirs = remoteDir.split("/");
    // 遍历文件夹
    for (String subDir : dirs) {
        // 文件夹字符串非空
        if (!subDir.isEmpty()) {
            // 切换工作目录
            if (!ftp.changeWorkingDirectory(subDir)) {
                // 若目录不存在则先创建
                if (!ftp.makeDirectory(subDir)) {
                    return false;
                }
                // 切换工作目录
                if (!ftp.changeWorkingDirectory(subDir)) {
                    return false;
                }
            }
        }
    }
    return true;
}
 
开发者ID:wyp0596,项目名称:elegant-springboot,代码行数:23,代码来源:MyFtpClient.java

示例13: deleteFile

import org.apache.commons.net.ftp.FTPClient; //导入依赖的package包/类
/**
 * 删除服务器上指定的文件
 * 
 * @author gaoxianglong
 */
public boolean deleteFile(File file) {
	boolean result = false;
	FTPClient ftpClient = ftpConnManager.getFTPClient();
	if (null == ftpClient || !ftpClient.isConnected()) {
		return result;
	}
	try {
		result = ftpClient.deleteFile(file.getName());
		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,代码行数:25,代码来源:FtpUtils.java

示例14: testFTPConnect

import org.apache.commons.net.ftp.FTPClient; //导入依赖的package包/类
/**
 * Simple test that connects to the inbuilt ftp server and logs on
 * 
 * @throws Exception
 */
public void testFTPConnect() throws Exception
{
    logger.debug("Start testFTPConnect");
    
    FTPClient ftp = connectClient();
    try
    {
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply))
        {
            fail("FTP server refused connection.");
        }
    
        boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN);
        assertTrue("admin login not successful", login);
    } 
    finally
    {
        ftp.disconnect();
    }       
}
 
开发者ID:Alfresco,项目名称:alfresco-repository,代码行数:28,代码来源:FTPServerTest.java

示例15: connectClient

import org.apache.commons.net.ftp.FTPClient; //导入依赖的package包/类
private FTPClient connectClient() throws IOException
{
    FTPClient ftp = new FTPClient();

    if(logger.isDebugEnabled())
    {
        ftp.addProtocolCommandListener(new PrintCommandListener(
                                   new PrintWriter(System.out)));
    }
    ftp.connect(HOSTNAME, ftpConfigSection.getFTPPort());
    return ftp;
}
 
开发者ID:Alfresco,项目名称:alfresco-repository,代码行数:13,代码来源:FTPServerTest.java


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