java实现FTP远程文件移动(重命名、复制、拷贝)

首先就标题说明一点,java使用org.apache.commons.net.ftp.ftpclient包来操作FTP是很爽滴,但对远程文件操作,好像没有实现

复制文件的方法。我用的是文件移动(move),把文件从一个文件夹移动到另外一个文件夹。

 

背景:

     在action中操作远程FTP,实现文件移动。程序运行在本机,FTP是一个Linux服务器。

 

实现:

     

      登录FTP并生成一个FTPClient对象如 fc,用方法rename(String1,String2)如下:

     

      fc.rename(file.getName(), "../ScheduleList/"+file.getName());

 

说明:

 

     把FTP上当前工作目录下的文件(file.getName()),移动到与当前目录平级的另一目录ScheduleList下。

     如果你只是想更改名称,那就写成fc.rename(file.getName(), "newName");

     移动文件只是在新文件名前加上路径,我设置了当前工作目录,所以这里用的是相对路径。

 

注意:

     

       action操作FTP时一定要注意中文编码问题,在action中显示为正常汉字的,用rename不一定正确。

       我的文件名是用FTPFile的getName获得的,在action中是乱码,所以用UTF-8转了一次,但是把转过码显示正常的文件名放在

 rename方法中就不对了,方法识别不了,rename不成功。包括你使用changeWorkingDirectory("path")更改工作目录时也一样,带汉字的字符串必须转码之后再作为参数。当然,这个时候你会发现你看到的参数是一些乱码,但是这些方法却能用。也就是说,你把从FTP上得到的东西转成正常显示的汉字了,但当你放参数给FTP方法时,又必须把它们转换回原来的编码。

Java文件复制(远程复制(网络传输),用于远程备份文件)(支持文件夹,嵌套子文件夹) import java.io.*; import java.util.*; public class FileSelection { private File rootDirectory;//根目录 private File[] fileList;//文件目录下面的文件列表(包括目录,用于多次判断) private ArrayList fileArrayList; // 用于存储文件(只是文件)列表 //初始化参数 public FileSelection() { fileArrayList=new ArrayList(); rootDirectory = new File("Test"); rootDirectory.mkdir(); } //获得文件(不包括目录)的列表 public void initFileArrayList() { if (rootDirectory.isDirectory()) { //遍历目录下面的文件和子目录 fileList = rootDirectory.listFiles(); for (int i = 0; i < fileList.length; i++) { //如果是文件,添加到文件列表中 if(fileList[i].isFile()){ fileArrayList.add(fileList[i]); } //否则递归遍历子目录 else if (fileList[i].isDirectory()) { fileList[i].mkdir(); rootDirectory=fileList[i]; initFileArrayList(); } } } } //将文件信息添加到列表中 public void addFiles(File f){ fileArrayList.add(f); } //访问器返回文件列表 public ArrayList getFileArrayList() { return fileArrayList; } } -------------------- BackupClient.java package com.xinxin.Client; import java.io.*; import java.net.*; /** * * @author Administrator *@version 1.0 *BackupClient实现文件的传输到服务器 */ public class BackupClient implements Runnable{ private int port;//服务器端口 private InetAddress ipAddress;//服务器IP地址 private Socket clientSocket;//客户端套接字 private InputStream inputStream;//网络输入流 private OutputStream outputStream;//网络输出流 private File file; //构造函数(获得服务器端IP地址和监听端口号) public BackupClient(InetAddress ipAddress,int port,File file){ this.ipAddress=ipAddress; this.port=port;
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); } } }
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值