JAVA操作FTP(FTP⼯具类)Java 操作 FTP、FTP⼯具类、Java实现FTP代码⽰例
导⼊commons-net
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
st;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import org.apachemons.ftp.FTP;
import org.apachemons.ftp.FTPClient;
import org.apachemons.ftp.FTPClientConfig;
import org.apachemons.ftp.FTPFile;
import org.apachemons.ftp.FTPReply;
public class Ftp {
private String Control_Encoding ="UTF-8";
private FTPClient client = null;
private String host ="";
private int port =21;
private String user ="";
private String password ="";
private String ftpPath ="/";
@SuppressWarnings("unused")
private Ftp(){
}
public Ftp(String host,int port, String user, String pwd){
this.host = host;
this.port = port;
this.user = user;
this.password = pwd;
}
/**
* 获取当前FTP所在⽬录位置
*
* @return
*/
public String getHome(){
return this.ftpPath;
}
/**
* 连接FTP Server
* @throws IOException
*/
public static final String ANONYMOUS_USER ="anonymous";
public void connect()throws Exception {
if(client == null){
client =new FTPClient();
}
/
/ 已经连接
if(client.isConnected()){
return;
}
// 编码
client.setControlEncoding(Control_Encoding);
try{
// 连接FTP Server
// 登陆
if(this.user == null ||"".equals(this.user)){
/
/ 使⽤匿名登陆
client.login(ANONYMOUS_USER, ANONYMOUS_USER);
}else{
client.login(this.user,this.password);
}
// 设置⽂件格式
client.setFileType(FTPClient.BINARY_FILE_TYPE);
// 获取FTP Server 应答
int reply = ReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){
client.disconnect();
throw new Exception("connection FTP fail!");
}
FTPClientConfig config =new SystemType().split(" ")[0]);  config.setServerLanguageCode("zh");
// 使⽤被动模式设为默认
// ⼆进制⽂件⽀持
client.setFileType(FTP.BINARY_FILE_TYPE);
// 设置模式
client.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
}catch(IOException e){
throw new Exception("connection FTP fail! "+ e);
}
}
/**
* 断开FTP连接
*
* @param ftpClient
* @throws IOException
*/
public void close(){
if(client != null && client.isConnected()){
try{
client.logout();
client.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
/**
* 获取⽂件列表
*
* @return
*/
public List<FTPFile>list(){
List<FTPFile> list = null;
try{
FTPFile ff[]= client.listFiles(ftpPath);
if(ff != null && ff.length >0){
list =new ArrayList<FTPFile>(ff.length);
Collections.addAll(list, ff);
}else{
list =new ArrayList<FTPFile>(0);
}
}catch(IOException e){
e.printStackTrace();
}
return list;
}
/**
* 切换⽬录
*
* @param path
*            需要切换的⽬录
* @param forcedIncrease
*            如果⽬录不存在,是否增加
*/
public void switchDirectory(String path,boolean forcedIncrease){ try{
if(path != null &&!"".equals(path)){
boolean ok = client.changeWorkingDirectory(path);
if(ok){
this.ftpPath = path;
}else if(forcedIncrease){
// ftpPath 不存在,⼿动创建⽬录
StringTokenizer token =new StringTokenizer(path,"\\//");
while(token.hasMoreTokens()){
String npath = Token();
client.makeDirectory(npath);
client.changeWorkingDirectory(npath);
if(ok){
this.ftpPath = path;
}
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 创建⽬录
*
* @param path
*/
public void createDirectory(String path){
try{
if(path != null &&!"".equals(path)){
boolean ok = client.changeWorkingDirectory(path);
if(!ok){
// ftpPath 不存在,⼿动创建⽬录
StringTokenizer token =new StringTokenizer(path,"\\//");
while(token.hasMoreTokens()){
String npath = Token();
client.makeDirectory(npath);
client.changeWorkingDirectory(npath);
}
}
}
client.changeWorkingDirectory(this.ftpPath);
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 删除⽬录,如果⽬录中存在⽂件或者⽂件夹则删除失败  *
* @param path
* @return
*/
public boolean deleteDirectory(String path){ boolean flag =false;
try{
flag = veDirectory(path);
}catch(IOException e){
e.printStackTrace();
}
return flag;
}
/**
* 删除⽂件
*
* @param path
* @return
*/
public boolean deleteFile(String path){
boolean flag =false;
try{
flag = client.deleteFile(path);
}catch(IOException e){
e.printStackTrace();
}
return flag;
}
/**
* 上传⽂件,上传⽂件只会传到当前所在⽬录
*
* @param localFile
*            本地⽂件
* @return
*/
public boolean upload(File localFile){
return this.upload(localFile,"");
}
/**
* 上传⽂件,会覆盖FTP上原有⽂件
*
* @param localFile
*            本地⽂件
* @param reName
*            重名
* @return
*/
public boolean upload(File localFile, String reName){ boolean flag =false;
String targetName = reName;
// 设置上传后⽂件名
if(reName == null ||"".equals(reName)){
targetName = Name();
}
FileInputStream fis = null;
try{
// 开始上传⽂件
fis =new FileInputStream(localFile);
client.setControlEncoding(Control_Encoding);
client.setFileType(FTPClient.BINARY_FILE_TYPE);
boolean ok = client.storeFile(targetName, fis);
if(ok){
flag =true;
}
}catch(IOException e){
e.printStackTrace();
}
return flag;
}
/**
* 下载⽂件,如果存在会覆盖原⽂件
*
* @param ftpFileName
*            ⽂件名称,FTP上的⽂件名称
* @param savePath
*            保存⽬录,本地保存⽬录
getsavefilename* @return
*/
public boolean download(String ftpFileName, String savePath){ boolean flag =false;
File dir =new File(savePath);
if(!ists()){
dir.mkdirs();
}
FileOutputStream fos = null;
try{
String saveFile = AbsolutePath()+ File.separator + ftpFileName;  fos =new FileOutputStream(new File(saveFile));
boolean ok = ieveFile(ftpFileName, fos);
if(ok){
flag =true;
}
}catch(IOException e){
e.printStackTrace();
}
return flag;
}
public static void main(String args[]){
// 创建FTP对象
Ftp ftp =new Ftp("127.0.0.1",21,"myftp","myftp@2020");
try{
// 连接FTP
// 移动⼯作空间、切换⽬录
System.out.println("当前位置:"+ Home());
ftp.switchDirectory("/test",true);
System.out.println("当前位置:"+ Home());
// 查询⽬录下的所有⽂件夹以及⽂件
List<FTPFile> list = ftp.list();

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。