Quick Easy FTP Server V4.0.0.exe.zip hfs_2.3m_build300.exe.7z
Jar包下载:commons-net-3.6.jar guava-28.2-jre.jar
Guava是一种基于开源的Java库,其中包含谷歌正在由他们很多项目使用的很多核心库。这个库是为了方便编码,并减少编码错误。这个库提供用于集合,缓存,支持原语,并发性,常见注解,字符串处理,I/O和验证的实用方法。
Guava 的好处:标准化 - Guava库是由谷歌托管;高效 - 可靠,快速和有效的扩展JAVA标准库;优化 -Guava库经过高度的优化;函数式编程 -增加JAVA功能和处理能力;实用程序 - 提供了经常需要在应用程序开发的许多实用程序类;验证 -提供标准的故障安全验证机制;最佳实践 - 强调最佳的做法;guava类似Apache Commons工具集。
Java使用Commons Net包进行FTP客户端操作,一般封装一个工具类,如下:
import java.io.*
import java.net.UnknownHostException;
import java.util.*
import org.apache.commons.net.ftp.*
import com.google.common.base.Strings;
/**
* 基于Commons Net包的FTP客户端工具类;
* @author Admin
*/
public class FTPTool {
private static final String DEFAULT_CHARSET = "UTF-8";
private static final int DEFAULT_TIMEOUT = 60 * 1000;
private final String host;
private final int port;
private final String username;
private final String password;
private FTPClient ftpClient;
private volatile String ftpBasePath;
private FTPTool(String host, String username, String password) {
this(host, 21, username, password, DEFAULT_CHARSET);
setTimeout(DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT);
}
private FTPTool(String host, int port, String username, String password, String charset) {
ftpClient = new FTPClient();
ftpClient.setControlEncoding(charset);
this.host = Strings.isNullOrEmpty(host) ? "localhost" : host;
this.port = (port <= 0) ? 21 : port;
this.username = Strings.isNullOrEmpty(username) ? "anonymous" : username;
this.password = password;
}
/**
* 创建FTP客户端实例
*/
public static FTPTool createFTPTool(String host, String username, String password) {
return new FTPTool(host, username, password);
}
/**
* 创建FTPd客户端实例;自定义端口、编码等;
*/
public static FTPTool createFTPTool(String host, int port, String username, String password, String charset) {
return new FTPTool(host, port, username, password, charset);
}
/**
* 设置超时时间
*/
public void setTimeout(int defaultTimeout, int connectTimeout, int dataTimeout) {
ftpClient.setDefaultTimeout(defaultTimeout);
ftpClient.setConnectTimeout(connectTimeout);
ftpClient.setDataTimeout(dataTimeout);
}
/**
* 连接FTP服务器 */
public void connect() throws IOException {
try {
ftpClient.connect(host, port);
} catch (UnknownHostException e) {
throw new IOException("Can't find FTP server :" + host);
}
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
disconnect();
throw new IOException("Can't connect to server :" + host);
}
if (!ftpClient.login(username, password)) {
disconnect();
throw new IOException("Can't login to server :" + host);
}
// set data transfer mode.
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// Use passive mode to pass firewalls.
ftpClient.enterLocalPassiveMode();
initFtpBasePath();
}
/**
* 连接ftp时保存刚登陆ftp时的路径
*/
private void initFtpBasePath() throws IOException {
if (Strings.isNullOrEmpty(ftpBasePath)) {
synchronized (this) {
if (Strings.isNullOrEmpty(ftpBasePath)) {
ftpBasePath = ftpClient.printWorkingDirectory();
}
}
}
}
/**
* 返回连接状态;
*/
public boolean isConnected() {
return ftpClient.isConnected();
}
/**
* 将指定输入流上传到服务器;****需要测试****
*/
public String uploadFileFromIS(String fileName, InputStream inputStream) throws IOException {
String uploadDir = "";
if (fileName.startsWith("/")) {
uploadDir = ftpBasePath + fileName.substring(0, fileName.lastIndexOf("/"));
} else {
uploadDir = printWorkingDirectory() + "/" + fileName.substring(0, fileName.lastIndexOf("/"));
}
makeDirs(uploadDir);
storeFile(fileName, inputStream);
return uploadDir + "/" + fileName.substring(fileName.lastIndexOf("/"), fileName.length());
}
/**
* 下载文件到指定输出流中
*/
public void downloadFileToOS(String filePath, OutputStream outputStream) throws IOException {
ftpClient.retrieveFile(filePath, outputStream);
}
/**
* 获取ftp上指定文件名到输出流中
*/
public void retrieveFile(String ftpFileName, OutputStream out) throws IOException {
try {
FTPFile[] fileInfoArray = ftpClient.listFiles(ftpFileName);
if (fileInfoArray == null || fileInfoArray.length == 0) {
throw new FileNotFoundException("File '" + ftpFileName + "' was not found on FTP server.");
}
FTPFile fileInfo = fileInfoArray[0];
if (fileInfo.getSize() > Integer.MAX_VALUE) {
throw new IOException("File '" + ftpFileName + "' is too large.");
}
if (!ftpClient.retrieveFile(ftpFileName, out)) {
throw new IOException("Error loading file '" + ftpFileName + "' from FTP server. Check FTP permissions and path.");
}
out.flush();
} finally {
closeStream(out);
}
}
/**
* 将输入流存储到指定的服务器路径下
*/
public void storeFile(String ftpFileName, InputStream in) throws IOException {
try {
if (!ftpClient.storeFile(ftpFileName, in)) {
throw new IOException("Can't upload file '" + ftpFileName + "' to FTP server. Check FTP permissions and path.");
}
} finally {
closeStream(in);
}
}
/**
* 根据服务器路径名称删除文件
*/
public void deleteFile(String ftpFileName) throws IOException {
if (!ftpClient.deleteFile(ftpFileName)) {
throw new IOException("Can't remove file '" + ftpFileName + "' from FTP server.");
}
}
/**
* 上传文件到服务器 */
public void upload(String ftpFileName, File localFile) throws IOException {
if (!localFile.exists()) {
throw new IOException("Can't upload '" + localFile.getAbsolutePath() + "'. This file doesn't exist.");
}
InputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(localFile));
if (!ftpClient.storeFile(ftpFileName, in)) {
throw new IOException("Can't upload file '" + ftpFileName + "' to FTP server. Check FTP permissions and path.");
}
} finally {
closeStream(in);
}
}
/**
* 上传文件夹到服务器上
*/
public void uploadDir(String remotePath, String localPath) throws IOException {
localPath = localPath.replace("\\\\", "/");
File file = new File(localPath);
if (file.exists()) {
if (!ftpClient.changeWorkingDirectory(remotePath)) {
ftpClient.makeDirectory(remotePath);
ftpClient.changeWorkingDirectory(remotePath);
}
File[] files = file.listFiles();
if (null != files) {
for (File f : files) {
if (f.isDirectory() && !f.getName().equals(".") && !f.getName().equals("..")) {
uploadDir(remotePath + "/" + f.getName(), f.getPath());
} else if (f.isFile()) {
upload(remotePath + "/" + f.getName(), f);
}
}
}
}
}
/**
* 下载文件到本地上
*/
public void download(String ftpFileName, File localFile) throws IOException {
OutputStream out = null;
try {
FTPFile[] fileInfoArray = ftpClient.listFiles(ftpFileName);
if (fileInfoArray == null || fileInfoArray.length == 0) {
throw new FileNotFoundException("File " + ftpFileName + " was not found on FTP server.");
}
FTPFile fileInfo = fileInfoArray[0];
if (fileInfo.getSize() > Integer.MAX_VALUE) {
throw new IOException("File " + ftpFileName + " is too large.");
}
out = new BufferedOutputStream(new FileOutputStream(localFile));
if (!ftpClient.retrieveFile(ftpFileName, out)) {
throw new IOException("Error loading file " + ftpFileName + " from FTP server. Check FTP permissions and path.");
}
out.flush();
} finally {
closeStream(out);
}
}
/**
* 改变工作目录,成功返回true
*/
public boolean changeWorkingDirectory(String dir) {
if (!ftpClient.isConnected()) {
return false;
}
try {
return ftpClient.changeWorkingDirectory(dir);
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* 下载服务器下文件夹到本地
*/
public void downloadDir(String remotePath, String localPath) throws IOException {
localPath = localPath.replace("\\\\", "/");
File file = new File(localPath);
if (!file.exists()) {
file.mkdirs();
}
FTPFile[] ftpFiles = ftpClient.listFiles(remotePath);
for (int i = 0; ftpFiles != null && i < ftpFiles.length; i++) {
FTPFile ftpFile = ftpFiles[i];
if (ftpFile.isDirectory() && !ftpFile.getName().equals(".") && !ftpFile.getName().equals("..")) {
downloadDir(remotePath + "/" + ftpFile.getName(), localPath + "/" + ftpFile.getName());
} else {
download(remotePath + "/" + ftpFile.getName(), new File(localPath + "/" + ftpFile.getName()));
}
}
}
/**
* 列出参数目录下的所有文件
*/
public List<String> listFileNames(String filePath) throws IOException {
FTPFile[] ftpFiles = ftpClient.listFiles(filePath);
List<String> fileList = new ArrayList<>();
if (ftpFiles != null) {
for (int i = 0; i < ftpFiles.length; i++) {
FTPFile ftpFile = ftpFiles[i];
if (ftpFile.isFile()) {
fileList.add(ftpFile.getName());
}
}
}
return fileList;
}
/**
* 发送ftp命令到ftp服务器中
*
*/
public void sendSiteCommand(String args) throws IOException {
if (!ftpClient.isConnected()) {
ftpClient.sendSiteCommand(args);
}
}
/**
* 获取当前所处的工作目录
*/
public String printWorkingDirectory() {
if (!ftpClient.isConnected()) {
return "";
}
try {
return ftpClient.printWorkingDirectory();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
/**
* 返回到当前工作目录的父目录下
*/
public boolean changeToParentDirectory() {
if (!ftpClient.isConnected()) {
return false;
}
try {
return ftpClient.changeToParentDirectory();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* 返回当前工作目录的上一级目录
*/
public String printParentDirectory() {
if (!ftpClient.isConnected()) {
return "";
}
String w = printWorkingDirectory();
changeToParentDirectory();
String p = printWorkingDirectory();
changeWorkingDirectory(w);
return p;
}
/**
* 创建目录
*/
public boolean makeDirectory(String pathname) throws IOException {
return ftpClient.makeDirectory(pathname);
}
/**
* 创建多级目录
*/
public void makeDirs(String pathname) throws IOException {
pathname = pathname.replace("\\\\", "/");
String[] pathnameArray = pathname.split("/");
for (String each : pathnameArray) {
if (!Strings.isNullOrEmpty(each)) {
ftpClient.makeDirectory(each);
ftpClient.changeWorkingDirectory(each);
}
}
}
/**
* 关闭流
*/
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 关闭FTP连接
*/
public void disconnect() {
if (null != ftpClient && ftpClient.isConnected()) {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
FTPTool使用代码:
FTPTool ftpTool = FTPTool.createFTPTool("127.0.0.1", "test", "a");
ftpTool.connect();
ftpTool.upload("T.png", new File("D:/A.jpg"));