package com.feng.utils; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; /** * @author songfeng * @version 1.0 * @since 2014-12-26 * @category com.feng.util */ public class FtpUtil { private FTPClient ftp; private boolean is_connected; public FtpUtil() { ftp = new FTPClient(); is_connected = false; } public FtpUtil(int defaultTimeoutSecond, int connectTimeoutSecond, int dataTimeoutSecond) { ftp = new FTPClient(); is_connected = false; ftp.setDefaultTimeout(defaultTimeoutSecond * 1000); ftp.setConnectTimeout(connectTimeoutSecond * 1000); ftp.setDataTimeout(dataTimeoutSecond * 1000); } /** * Connects to FTP server. * * @param host * FTP server address or name * @param port * FTP server port * @param user * user name * @param password * user password * @param isTextMode * text / binary mode switch * @throws IOException * on I/O errors */ public void connect(String host, int port, String user, String password, boolean isTextMode) throws IOException { // Connect to server. try { ftp.connect(host, port); } catch (UnknownHostException ex) { throw new IOException("Can't find FTP server '" + host + "'"); } // Check rsponse after connection attempt. int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { disconnect(); throw new IOException("Can't connect to server '" + host + "'"); } // Login. if (!ftp.login(user, password)) { is_connected = false; disconnect(); throw new IOException("Can't login to server '" + host + "'"); } else { is_connected = true; } // Set data transfer mode. if (isTextMode) { ftp.setFileType(FTP.ASCII_FILE_TYPE); } else { ftp.setFileType(FTP.BINARY_FILE_TYPE); } } /** * Uploads the file to the FTP server. * * @param ftpFileName * server file name (with absolute path) * @param localFile * local file to upload * @throws IOException * on I/O errors */ public void upload(String ftpFileName, File localFile) throws IOException { // File check. if (!localFile.exists()) { throw new IOException("Can't upload '" + localFile.getAbsolutePath() + "'. This file doesn't exist."); } // Upload. InputStream in = null; try { // Use passive mode to pass firewalls. ftp.enterLocalPassiveMode(); in = new BufferedInputStream(new FileInputStream(localFile)); if (!ftp.storeFile(ftpFileName, in)) { throw new IOException("Can't upload file '" + ftpFileName + "' to FTP server. Check FTP permissions and path."); } } finally { try { in.close(); } catch (IOException ex) { } } } /** * Downloads the file from the FTP server. * * @param ftpFileName * server file name (with absolute path) * @param localFile * local file to download into * @throws IOException * on I/O errors */ public void download(String ftpFileName, File localFile) throws IOException { // Download. OutputStream out = null; try { // Use passive mode to pass firewalls. ftp.enterLocalPassiveMode(); // Get file info. FTPFile[] fileInfoArray = ftp.listFiles(ftpFileName); if (fileInfoArray == null) { throw new FileNotFoundException("File " + ftpFileName + " was not found on FTP server."); } // Check file size. FTPFile fileInfo = fileInfoArray[0]; long size = fileInfo.getSize(); if (size > Integer.MAX_VALUE) { throw new IOException("File " + ftpFileName + " is too large."); } // Download file. out = new BufferedOutputStream(new FileOutputStream(localFile)); if (!ftp.retrieveFile(ftpFileName, out)) { throw new IOException("Error loading file " + ftpFileName + " from FTP server. Check FTP permissions and path."); } out.flush(); } finally { if (out != null) { try { out.close(); } catch (IOException ex) { } } } } /** * Removes the file from the FTP server. * * @param ftpFileName * server file name (with absolute path) * @throws IOException * on I/O errors */ public void remove(String ftpFileName) throws IOException { if (!ftp.deleteFile(ftpFileName)) { throw new IOException("Can't remove file '" + ftpFileName + "' from FTP server."); } } /** * Lists the files in the given FTP directory. * * @param filePath * absolute path on the server * @return files relative names list * @throws IOException * on I/O errors */ public List<String> list(String filePath) throws IOException { List<String> fileList = new ArrayList<String>(); // Use passive mode to pass firewalls. ftp.enterLocalPassiveMode(); FTPFile[] ftpFiles = ftp.listFiles(filePath); int size = (ftpFiles == null) ? 0 : ftpFiles.length; for (int i = 0; i < size; i++) { FTPFile ftpFile = ftpFiles[i]; if (ftpFile.isFile()) { fileList.add(ftpFile.getName()); } } return fileList; } /** * Sends an FTP Server site specific command * * @param args * site command arguments * @throws IOException * on I/O errors */ public void sendSiteCommand(String args) throws IOException { if (ftp.isConnected()) { try { ftp.sendSiteCommand(args); } catch (IOException ex) { } } } /** * Disconnects from the FTP server * * @throws IOException * on I/O errors */ public void disconnect() throws IOException { if (ftp.isConnected()) { try { ftp.logout(); ftp.disconnect(); is_connected = false; } catch (IOException ex) { } } } /** * Makes the full name of the file on the FTP server by joining its path and the local * file name. * * @param ftpPath * file path on the server * @param localFile * local file * @return full name of the file on the FTP server */ public String makeFTPFileName(String ftpPath, File localFile) { if (ftpPath == "") { return localFile.getName(); } else { String path = ftpPath.trim(); if (path.charAt(path.length() - 1) != '/') { path = path + "/"; } return path + localFile.getName(); } } /** * Test coonection to ftp server * * @return true, if connected */ public boolean isConnected() { return is_connected; } /** * Get current directory on ftp server * * @return current directory */ public String getWorkingDirectory() { if (!is_connected) { return ""; } try { return ftp.printWorkingDirectory(); } catch (IOException e) { } return ""; } /** * Set working directory on ftp server * * @param dir * new working directory * @return true, if working directory changed */ public boolean setWorkingDirectory(String dir) { if (!is_connected) { return false; } try { return ftp.changeWorkingDirectory(dir); } catch (IOException e) { } return false; } /** * Change working directory on ftp server to parent directory * * @return true, if working directory changed */ public boolean setParentDirectory() { if (!is_connected) { return false; } try { return ftp.changeToParentDirectory(); } catch (IOException e) { } return false; } /** * Get parent directory name on ftp server * * @return parent directory */ public String getParentDirectory() { if (!is_connected) { return ""; } String w = getWorkingDirectory(); setParentDirectory(); String p = getWorkingDirectory(); setWorkingDirectory(w); return p; } /** * Get file from ftp server into given output stream * * @param ftpFileName * file name on ftp server * @param out * OutputStream * @throws IOException */ public void getFile(String ftpFileName, OutputStream out) throws IOException { try { // Use passive mode to pass firewalls. ftp.enterLocalPassiveMode(); // Get file info. FTPFile[] fileInfoArray = ftp.listFiles(ftpFileName); if (fileInfoArray == null) { throw new FileNotFoundException("File '" + ftpFileName + "' was not found on FTP server."); } // Check file size. FTPFile fileInfo = fileInfoArray[0]; long size = fileInfo.getSize(); if (size > Integer.MAX_VALUE) { throw new IOException("File '" + ftpFileName + "' is too large."); } // Download file. if (!ftp.retrieveFile(ftpFileName, out)) { throw new IOException("Error loading file '" + ftpFileName + "' from FTP server. Check FTP permissions and path."); } out.flush(); } finally { if (out != null) { try { out.close(); } catch (IOException ex) { } } } } /** * Put file on ftp server from given input stream * * @param ftpFileName * file name on ftp server * @param in * InputStream * @throws IOException */ public void putFile(String ftpFileName, InputStream in) throws IOException { try { // Use passive mode to pass firewalls. ftp.enterLocalPassiveMode(); if (!ftp.storeFile(ftpFileName, in)) { throw new IOException("Can't upload file '" + ftpFileName + "' to FTP server. Check FTP permissions and path."); } } finally { try { in.close(); } catch (IOException ex) { } } } public void getFileInfo(String filePath) { InputStream inputStream = null; BufferedReader in = null; try { ftp.enterLocalPassiveMode(); inputStream = ftp.retrieveFileStream(filePath); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); in = new BufferedReader(inputStreamReader); String fileContent = ""; String str = null; while((str = in.readLine()) != null) { fileContent += str; fileContent += "\n"; } System.out.println(fileContent); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { try { FtpUtil ftpClient = new FtpUtil(30, 3, 30); ftpClient.connect("x.x.x.x", 21, "xxx", "xxx", true); System.out.println(ftpClient.list("/export/home/"));; } catch (IOException e) { e.printStackTrace(); } } }
以上为FTP工具类
下面是SFTP工具类
package com.feng.utils; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Vector; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.ChannelSftp.LsEntry; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; public class SFtpUtil { public static void main(String[] args) { listFileNames("x.x.x.x", 22, "xxx", "xxx", "/root/"); } private static List<String> listFileNames(String host, int port, String username, final String password, String dir) { List<String> list = new ArrayList<String>(); ChannelSftp sftp = null; Channel channel = null; Session sshSession = null; try { JSch jsch = new JSch(); jsch.getSession(username, host, port); sshSession = jsch.getSession(username, host, port); sshSession.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); channel = sshSession.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; Vector<?> vector = sftp.ls(dir); for (Object item : vector) { LsEntry entry = (LsEntry) item; System.out.println(entry.getFilename()); } } catch (Exception e) { e.printStackTrace(); } finally { closeChannel(sftp); closeChannel(channel); closeSession(sshSession); } return list; } private static void closeChannel(Channel channel) { if (channel != null) { if (channel.isConnected()) { channel.disconnect(); } } } private static void closeSession(Session session) { if (session != null) { if (session.isConnected()) { session.disconnect(); } } } }
相关推荐
ftp工具类,构造方法初始化类,连接ftp,列出所有文件内容,下载文件
FTP 工具类,赚钱积分下载东西,谢谢各位!谢谢各位!
ftp工具类,帮助你很容易的实现ftp功能
java操作FTP工具类:实现基本断点上传下载、实现上传下载进度汇报、实现中文目录创建及中文文件创建,添加对于中文的支持
FTP工具类,包括:文件夹上传下载,文件删除(包括非空文件夹),重命名等操作 基本的操作应该都有
在本文中,我们将深入探讨如何利用这个库开发一个FTP工具类,以便在Java应用程序中进行文件上传、下载和其他FTP操作。 首先,我们需要了解FTP的基本概念。FTP是一种用于在网络上进行文件传输的标准协议。它允许用户...
ftp操作工具类,用户ftp文件的添加,删除,等操作!
Java ftp工具类,可以实现ftp上传,读取,目录切换,内容创建,目录创建、检查文件是否存在,支持主动方式和被动方式读取
jdk1.7以上专用FTP工具类,本人花了半天时间调试通过,拿来即用,具体用法详见main函数。
对于初学者来说,理解并使用这样的FTP工具类可以帮助他们快速掌握FTP操作,避免了重复编写相同功能的代码。同时,这个工具类也展示了如何在Java中利用第三方库(如Apache Commons Net)来扩展Java标准库的功能。 ...
接下来,我们将深入探讨FTP工具类的主要功能、使用方法以及源码分析。 **1. FTPClient类** FTPClient是Apache Commons Net的核心类,它实现了FTP协议的大部分功能。通过这个类,我们可以连接到FTP服务器,执行登录...
本篇文章将详细讲解如何使用Java编写一个FTP工具类,实现连接FTP服务器、上传文件、删除文件、下载文件以及检索文件的功能。 首先,我们需要引入Apache Commons Net库,该库提供了丰富的FTP客户端API。在`pom.xml`...
Apache FTPClient操作FTP工具类
本话题将详细介绍如何使用Java实现FTP工具类以及所需的jar包。 Apache Commons Net是一个强大的Java网络实用程序库,它提供了多种网络协议的实现,包括FTP。在这个场景中,`commons-net-3.3.jar`是这个库的一个版本...
org.apache.commons.net.ftp.FTPClient FTP工具类,实现上传、下载、压缩到输出流下载等功能
Java FTP工具类是Java开发中用于处理FTP(File Transfer Protocol)协议的一种实用程序,它使得在Java应用程序中上传、下载、删除或者管理远程服务器上的文件变得简单。在本压缩包中,我们有一个名为"util"的文件,...
ftp 上传时,用到的工具类,项目上配置好ftp服务器后,controller可以方便的调用此工具类进行上传
ftp工具类,包含文件上传,文件删除,文件列表,查询当天文件类表方法
java的ftp工具类,需要的自行下载查看,有切换目录,创建目录方法。
本文将详细介绍标题和描述中提到的几个关键知识点:Java中的zip、rar(包括处理带密码的RAR文件)、gz压缩,以及FTP工具类的使用。 1. **Java ZIP压缩与解压缩**: Java内置的`java.util.zip`包提供了处理ZIP文件...