JAVA中使用FTPClient实现FTP上文件的操作

在JAVA项目中,经常需要做一些FTP的操作,如向FTP上传文件、下载文件、文件重命名、文件删除、创建文件夹等等,本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载重命名等操作文件。

如果是使用MAVEN管理项目则添加

<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-ftp</artifactId>
<version>2.13.2</version>
</dependency>


如果是普通的Java项目则需要添加camel-ftp-2.13.2.jar、camel-core-2.13.2.jar两个jar包


package cn.com.bestpay.pgw.zhpk;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;


//int port 为FTP的端口号   默认为21  


public class FtpUtils {


/**
* ftp上传单个文件
* @param ftpUrlftp地址
* @param userNameftp的用户名
* @param passwordftp的密码
* @param directory上传至ftp的路径名不包括ftp地址
* @param srcFileName要上传的文件全路径名
* @param destName上传至ftp后存储的文件名
* @throws IOException 
*/
public static boolean upload(String logSeq,String ftpUrl,String userName,int port,
String password,String directory,String srcFileName,String destName) throws IOException {
FTPClient ftpClient = new FTPClient();
FileInputStream fis = null;
boolean result = false;
try {
ftpClient.connect(ftpUrl,port);
ftpClient.login(userName, password);
ftpClient.enterLocalPassiveMode();
File srcFile = new File(srcFileName);
fis = new FileInputStream(srcFile);
// 设置上传目录
ftpClient.changeWorkingDirectory(directory);
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("gbk");
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
result = ftpClient.storeFile(destName, fis);
return result;
} catch(NumberFormatException e){
System.out.println("FTP端口配置错误:不是数字:" );
throw e;
} catch(FileNotFoundException e){
throw new FileNotFoundException();
} catch (IOException e) {
throw new IOException(e);
} finally {
IOUtils.closeQuietly(fis);
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}


/**
* FTP单个文件下载                                            
* @param ftpUrl         ftp地址                 
* @param userName                ftp的用户名               
* @param password                ftp的密码                
* @param directory               要下载的文件所在ftp的路径名不包含ftp地址    
* @param destFileName            要下载的文件名           
* @param downloadName            下载后锁存储的文件名全路径         
*/
public static boolean download(String logSeq,String ftpUrl,String userName,int port,
String password,String directory,String destFileName,String downloadName)throws IOException {
FTPClient ftpClient = new FTPClient();
boolean result = false;
try {
ftpClient.connect(ftpUrl,port);
ftpClient.login(userName, password);
ftpClient.enterLocalPassiveMode();
ftpClient.setBufferSize(1024);
// 设置文件类型(二进制)
ftpClient.changeWorkingDirectory(directory);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

System.out.println("destFileName:" + destFileName + ",downloadName:" + downloadName);
result = ftpClient.retrieveFile(destFileName, new FileOutputStream(downloadName));
return result;
} catch(NumberFormatException e){
throw e;
} catch(FileNotFoundException e){
throw new FileNotFoundException();
} catch (IOException e) {
throw new IOException(e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}

/**

* @param ftpUrl          ftp地址                            
* @param userName                 ftp的用户名                          
* @param password                 ftp的密码                           
* @param directory                要重命名的文件所在ftp的路径名不包含ftp地址          
* @param oldFileName              要重命名的文件名                          
* @param newFileName              重命名后的文件名                  
* @throws IOException 
*/
public static boolean rename(String logSeq,String ftpUrl,String userName,int port,
String password,String directory, String oldFileName, String newFileName) throws IOException {
/**
* 判断远程文件是否重命名成功,如果成功返回true,否则返回false
*/
boolean result = false;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(ftpUrl,port);
ftpClient.login(userName, password);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(directory);
result = ftpClient.rename(oldFileName, newFileName);//重命名远程文件
return result;
} catch(NumberFormatException e){
throw e;
} catch (IOException e) {
throw new IOException("连接ftp服务器失败!", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}

/**                                                                                         
*                                          
* @param ftpUrl                          ftp地址                                                     
* @param userName                        ftp的用户名                                                   
* @param password                        ftp的密码                                                    
* @param directory                       要删除的文件所在ftp的路径名不包含ftp地址                                  
* @param fileName                        要删除的文件名                                                   
* @return
* @throws IOException 
*/
public static boolean remove(String logSeq,String ftpUrl,String userName,int port,
String password,String directory, String fileName) throws IOException
{
/**
* 判断远程文件是否移除成功,如果成功返回true,否则返回false
*/
boolean result = false;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(ftpUrl,port);
ftpClient.login(userName, password);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(directory);
result = ftpClient.deleteFile(fileName);//删除远程文件
return result;
} catch(NumberFormatException e){
throw e;
} catch (IOException e) {
throw new IOException("连接ftp服务器失败!", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}

/**
*                                                               
* @param ftpUrl              ftp地址                              
* @param userName            ftp的用户名                            
* @param password            ftp的密码                             
* @param directory           要创建的目录所在ftp的路径名不包含ftp地址            
* @param newDirectory    要创建的新目录名
* @return
* @throws IOException 
*/
public static boolean makeDirecotory(String logSeq,String ftpUrl,String userName,int port,
String password,String directory, String newDirectory) throws IOException
{
/**
* 判断远程文件是否移除成功,如果成功返回true,否则返回false
*/
boolean result = false;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(ftpUrl,port);
ftpClient.login(userName, password);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(directory);
result = ftpClient.makeDirectory(newDirectory);//创建新目录
return result;
} catch(NumberFormatException e){
throw e;
} catch (IOException e) {
throw new IOException("连接ftp服务器失败!", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}

/**

* @param ftpUrl            ftp地址                                 
* @param userName         ftp的用户名                               
* @param password         ftp的密码                                
* @param directory         要重命名的目录所在ftp的路径名不包含ftp地址               
* @param oldDirectory         要重命名的旧目录名                           
* @param newDirectory重命名后的新目录
* @return
* @throws IOException 
*/
public static boolean renameDirecotory(String logSeq,String ftpUrl,String userName,int port,
String password,String directory,String oldDirectory,String newDirectory) throws IOException
{
/**
* 判断远程文件是否移除成功,如果成功返回true,否则返回false
*/
boolean result = false;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(ftpUrl,port);
ftpClient.login(userName, password);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(directory);
result = ftpClient.rename(oldDirectory,newDirectory);//重命名目录
return result;
} catch(NumberFormatException e){
throw e;
} catch (IOException e) {
throw new IOException("连接ftp服务器失败!", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}

/**

* @param ftpUrl                        ftp地址                              
* @param userName                      ftp的用户名                            
* @param password                      ftp的密码                             
* @param directory                     要重命名的目录所在ftp的路径名不包含ftp地址           
* @param deldirectory                  要删除的目录名                      
* @return                                              
* @throws IOException 
*/
public static boolean removeDirecotory(String logSeq,String ftpUrl,String userName,int port,
String password,String directory,String deldirectory) throws IOException
{
/**
* 判断远程文件是否移除成功,如果成功返回true,否则返回false
*/
boolean result = false;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(ftpUrl,port);
ftpClient.login(userName, password);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(directory);
result = ftpClient.removeDirectory(deldirectory);//删除目录
return result;
} catch(NumberFormatException e){
throw e;
} catch (IOException e) {
throw new IOException("连接ftp服务器失败!", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}

/**

* @param ftpUrl
* @param userName
* @param password
* @param directory
* @return
* @throws IOException 
*/
public static String[] list(String logSeq,String ftpUrl,String userName,int port,
String password,String directory) throws IOException
{
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(ftpUrl,port);
ftpClient.login(userName, password);
ftpClient.enterLocalPassiveMode();
ftpClient.setControlEncoding("gbk");
ftpClient.changeWorkingDirectory(directory);
ftpClient.enterLocalPassiveMode();
String[] list = ftpClient.listNames();//删除目录
return list;
} catch(NumberFormatException e){
throw e;
} catch (IOException e) {
throw new IOException("连接ftp服务器失败!", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}

}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用Java的网络编程功能,实现FTP协议的文件上传。具体步骤如下: 1. 建立与FTP服务器的连接:使用Java的Socket类进行连接,并使用该类的方法登录到FTP服务器。 2. 设置上传模式:使用FTP协议的特定命令设置上传模式为二进制模式。 3. 构造文件使用Java的FileInputStream类读取待上传的文件,并将其写入到FTP服务器。 4. 确认文件上传:使用FTP协议的特定命令确认文件已经成功上传。 5. 断开连接:使用Java的Socket类断开与FTP服务器的连接。 可以使用现成的开源FTP客户端库,如Apache Commons Net,简化开发难度。 ### 回答2: 要使用Java实现FTP文件上传,你需要使用JavaFTP库或框架。以下是一种可能的实现方式: 首先,需要引入FTP库或框架的相关依赖。比较常用的库包括Apache Commons Net和Apache FTPClient。你可以在项目的构建文件(比如Maven的pom.xml文件添加相应的依赖。 接下来,你需要建立FTP连接。使用FTPClient类的connect()方法连接到FTP服务器。你需要提供FTP服务器的主机名、端口号、用户名和密码。 一旦连接成功,你可以使用FTPClient的setFileType()方法设置文件类型,如二进制文件或文本文件。 然后,你可以使用changeWorkingDirectory()方法切换到FTP服务器上的目标目录,比如上传文件的目录。 之后,你可以使用storeFile()方法上传文件。该方法的参数是本地文件的路径和文件名,以及在FTP服务器上的文件名。 在上传过程,你可以使用FTPClient的进度监听器获取上传进度并进行相应的处理。比如,你可以实现一个ProgressListener接口的类,重写bytesTransferred()方法,在方法显示或记录上传进度。 最后,上传完成后,你需要使用disconnect()方法关闭FTP连接。 需要注意的是,在实际的使用,你还需要处理异常、处理上传失败的情况、上传大文件时的断点续传等场景。这些细节根据具体的需求和使用情况可能会有所不同。 总结起来,实现FTP文件上传的步骤包括连接FTP服务器、设置文件类型、切换目录、上传文件,并考虑上传进度、异常处理和关闭连接等。使用JavaFTP库或框架可以简化这些操作,提高开发效率。 ### 回答3: Java实现FTP文件上传可以通过使用Apache Commons Net库来实现。以下是一个简单的示例代码: ```java import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class FTPFileUploader { private String server; private int port; private String username; private String password; public FTPFileUploader(String server, int port, String username, String password) { this.server = server; this.port = port; this.username = username; this.password = password; } public void uploadFile(String localFilePath, String remoteFilePath) { FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); ftpClient.login(username, password); ftpClient.enterLocalPassiveMode(); File localFile = new File(localFilePath); FileInputStream fileInputStream = new FileInputStream(localFile); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.storeFile(remoteFilePath, fileInputStream); ftpClient.logout(); } catch (IOException e) { e.printStackTrace(); } finally { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { String server = "ftp.example.com"; int port = 21; String username = "your-username"; String password = "your-password"; String localFilePath = "path/to/local/file"; String remoteFilePath = "path/to/remote/file"; FTPFileUploader fileUploader = new FTPFileUploader(server, port, username, password); fileUploader.uploadFile(localFilePath, remoteFilePath); } } ``` 在这个示例代码,首先创建了一个FTPClient对象,然后连接到指定的FTP服务器。调用`login`方法进行登录验证,并通过`enterLocalPassiveMode`方法进入被动模式。接着打开本地文件输入流,设置FTP传输类型为二进制文件类型,使用`storeFile`方法将本地文件上传到指定的远程路径。最后关闭连接。 在使用这个示例代码时,需要将FTP服务器的地址、端口、用户名和密码替换为实际的值,并指定本地文件路径和远程文件路径。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值