java实现ftp的移动

使用的 是ftp4j
先来写一登录示例,然后根据此分别来说各种操作的示例代码:

Java代码
package test;
import it.sauronsoftware.ftp4j.FTPClient;
/**
* FTP操作测试
* @说明
* @author cuisuqiang
* @version 1.0
* @since
*/
public class Ftp4jTest {
public static void main(String[] args) {
try {
// 创建客户端
FTPClient client = new FTPClient();
// 不指定端口,则使用默认端口21
client.connect("192.168.1.122", 21);
// 用户登录
client.login("123", "123123");
// 打印地址信息
System.out.println(client);
} catch (Exception e) {
e.printStackTrace();
}
}
}


登录进行退出操作:

Java代码
// 安全退出
client.disconnect(true);
// 强制退出
client.disconnect(false);


获得当前文件夹路径:

Java代码
// 当前文件夹
String dir = client.currentDirectory();
System.out.println(dir);


创建目录

Java代码
// 创建目录
client.createDirectory("123");


切换文件夹路径,可以使用绝对路径或者是相对路径,相对路径就是相对与当前所在的路径:

Java代码
// 改变当前文件夹 绝对路径
// client.changeDirectory(dir + "/123");
// 改变当前文件夹 相对路径
client.changeDirectory("123");
// 当前文件夹
dir = client.currentDirectory();
System.out.println(dir);


返回上级目录
Java代码
client.changeDirectoryUp();
// 重新获得 当前文件夹
dir = client.currentDirectory();
System.out.println(dir);


重命名文件或文件夹

Java代码
client.rename("123", "456");


删除目录(不能删除非空目录) 绝对或相对路径

Java代码
client.deleteDirectory("456");


移动文件或文件夹

Java代码
client.rename("readme.txt", dir + "/456/readme.txt");


删除文件

Java代码
client.deleteFile(dir + "/456/readme.txt");


罗列当前目录下的文件和文件的修改日期,注意不要操作 . 和 .. 文件

Java代码
// 浏览文件
FTPFile[] list = client.list();
// 使用通配浏览文件
// FTPFile[] list = client.list("*.txt");
// 显示文件或文件夹的修改时间 你不能获得 . 或 .. 的修改日期,否则Permission denied
for(FTPFile f : list){
if(!f.getName().equals(".") && !f.getName().equals("..")){
System.out.print(f.getName() + "\t");
System.out.println(client.modifiedDate(f.getName()));
}
}


下载文件

Java代码
File file = new File("C:\\localFile.txt");
client.download("remoteFile.txt", file);


上传文件到当前目录

Java代码
client.upload(file);


监听文件传输状态
创建一个实现FTPDataTransferListener接口的类:
Java代码
/**
* 监听文件传输的状态,上传下载时最后一个参数
* @说明
* @author cuisuqiang
* @version 1.0
* @since
*/
class MyTransferListener implements {

// 文件开始上传或下载时触发
public void started() {
System.out.println("started");
}
// 显示已经传输的字节数
public void transferred(int length) {
System.out.println(length);
}
// 文件传输完成时,触发
public void completed() {
System.out.println("completed");
}
// 传输放弃时触发
public void aborted() {
System.out.println("aborted");
}
// 传输失败时触发
public void failed() {
System.out.println("failed");
}
}

然后在上传或下载时增加一个参数即可,例如上传时:
Java代码
client.upload(file, new MyTransferListener());


/**
* 判断当前为文件还是目录
*
* @param client
* FTP客户端对象
* @param dir
* 文件或目录
* @return -1、文件或目录不存在 0、文件 1、目录
* @throws Exception
*/
private static int getFileType(FTPClient client, String dir)
throws Exception {
FTPFile[] files = null;
try {
files = client.list(dir);
} catch (Exception e) {
return -1;
}
if (files.length > 1) {
return FTPFile.TYPE_DIRECTORY;
} else if (files.length == 1) {
FTPFile f = files[0];
if (f.getType() == FTPFile.TYPE_DIRECTORY) {
return FTPFile.TYPE_DIRECTORY;
}
String path = dir + "/" + f.getName();
try {
int len = client.list(path).length;
if (len == 1) {
return FTPFile.TYPE_DIRECTORY;
} else {
return FTPFile.TYPE_FILE;
}
} catch (Exception e) {
return FTPFile.TYPE_FILE;
}
} else {
try {
client.changeDirectory(dir);
client.changeDirectoryUp();
return FTPFile.TYPE_DIRECTORY;
} catch (Exception e) {
return -1;
}
}
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
public class FTPUtil { private FTPClient ftpClient=null; private boolean result = false; private FileInputStream fis; String ftpHost = "10.16.111.111"; String port = 21 String ftpUserName = "ftpuser11; String ftpPassword = "1234561"; /** * 登录服务器 * @param ftpInfo * @return * @throws IOException */ public FTPClient login() throws IOException { ftpClient = new FTPClient(); ftpClient.connect(ftpHost); boolean login = ftpClient.login(ftpUserName,ftpPassword); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); } if(login){ System.out.println("ftp连接成功!"); }else{ System.out.println("ftp连接失败!"); } //ftpClient.setControlEncoding("GBK"); return ftpClient; } /** * 字符串作为文件上传指定目录 下 * @param content 源字符串 * @param uploadDir 上传目录 * @param ftpFileName 上传文件名称 * @throws Exception */ public void ftpUploadByText(String content ,String uploadDir,String ftpFileName) throws Exception{ try { ftpClient = this.login(); //创建目录 createDir(ftpClient,uploadDir); // 设置上传目录 这个也应该用配置文件读取 ftpClient.changeWorkingDirectory(uploadDir); ftpClient.setBufferSize(1024); ftpClient.setControlEncoding("GBK"); // 设置文件类型(二进制) ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); String fileName = new String(ftpFileName.getBytes("GBK"),"iso-8859-1"); OutputStream os = ftpClient.storeFileStream(fileName); byte[] bytes = content.getBytes(); os.write(bytes); os.flush(); os.close(); } catch (Exception e) { ftpClient.disconnect(); ftpClient = null; e.printStackTrace(); throw e; }finally{ ftpClient.disconnect(); ftpClient = null; } } /** * 移动文件 * @param ftpInfo * @return * @throws Exception */ public boolean moveFile(FTPInfo ftpInfo)throws Exception { boolean flag = false; try { ftpClient = this.login(); flag = this.moveFile(ftpClient, ftpInfo.getChangeWorkingDirectoryPath(), ftpInfo.getFilePath()); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { ftpClient.disconnect(); ftpClient = null; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("关闭FTP连接发生异常!", e); }catch (Exception e) { e.printStackTrace(); throw e; } } return flag; } /** * 删除文件 * @param ftpInfo * @return * @throws Exception */ public boolean deleteFile(FTPInfo ftpInfo)throws Exception { boolean flag = false; try { ftpClient = this.login(); flag = this.deleteByFolder(ftpClient, ftpInfo.getChangeWorkingDirectoryPath()); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { ftpClient.disconnect(); ftpClient = null; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("关闭FTP连接发生异常!", e); }catch (Exception e) { e.printStackTrace(); throw e; } } return flag; } /** * 实现文件的移动,这里做的是一个文件夹下的所有内容移动到新的文件, * 如果要做指定文件移动,加个判断判断文件名 * 如果不需要移动,只是需要文件重命名,可以使用ftp.rename(oleName,newName) * @param ftp * @param oldPath * @param newPath * @return */ public boolean moveFile(FTPClient ftp,String oldPath,String newPath){ boolean flag = false; try { ftp.changeWorkingDirectory(oldPath); ftp.enterLocalPassiveMode(); //获取文件数组 FTPFile[] files = ftp.listFiles(); //新文件夹不存在则创建 if(!ftp.changeWorkingDirectory(newPath)){ ftp.makeDirectory(newPath); } //回到原有工作目录 ftp.changeWorkingDirectory(oldPath); for (FTPFile file : files) { if(file.isDirectory()) { moveFile(ftp,oldPath+file.getName()+"/" ,newPath+file.getName()+"/"); }else{ //转存目录 flag = ftp.rename(oldPath+new String(file.getName().getBytes("GBK"),"ISO-8859-1"), newPath+"/"+new String(file.getName().getBytes("GBK"),"ISO-8859-1")); } if(flag){ System.out.println(file.getName()+"移动成功"); }else{ System.out.println(file.getName()+"移动失败"); } } ftp.removeDirectory(new String(oldPath.getBytes("GBK"),"ISO-8859-1")); } catch (Exception e) { e.printStackTrace(); System.out.println("移动文件失败"); } return flag; } /** * 删除FTP上指定文件夹下文件及其子文件方法,添加了对中文目录的支持 * @param ftp FTPClient对象 * @param FtpFolder 需要删除的文件夹 * @return */ public boolean deleteByFolder(FTPClient ftp,String FtpFolder){ boolean flag = false; try { ftp.changeWorkingDirectory(new String(FtpFolder.getBytes("GBK"),"ISO-8859-1")); ftp.enterLocalPassiveMode(); FTPFile[] files = ftp.listFiles(); for (FTPFile file : files) { //判断为文件则删除 if(file.isFile()){ ftp.deleteFile(FtpFolder+new String(file.getName().getBytes("GBK"),"ISO-8859-1")); } //判断是文件夹 if(file.isDirectory()){ String childPath = FtpFolder +file.getName()+ "/"; //递归删除子文件夹 deleteByFolder(ftp,childPath); } } //循环完成后删除文件夹 flag = ftp.removeDirectory(new String(FtpFolder.getBytes("GBK"),"ISO-8859-1")); if(flag){ System.out.println(FtpFolder+"文件夹删除成功"); }else{ System.out.println(FtpFolder+"文件夹删除成功"); } } catch (Exception e) { e.printStackTrace(); System.out.println("删除失败"); } return flag; } /** * 创建目录 * @param createpath * @param sftp */ public void createDir(FTPClient ftpClient,String createpath) throws Exception { try { if(ftpClient.changeWorkingDirectory(createpath)) { return; } String pathArry[] = createpath.split("/"); StringBuffer filePath = new StringBuffer("/"); for (String path : pathArry) { if (path.equals("")) { continue; } filePath.append(path + "/"); if(!ftpClient.changeWorkingDirectory(filePath.toString())) { ftpClient.makeDirectory(filePath.toString()); ftpClient.changeWorkingDirectory(filePath.toString()); } } ftpClient.changeWorkingDirectory(createpath); }catch (Exception e) { e.printStackTrace(); throw new Exception("创建路径错误:" + createpath); } } }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值