码迷,mamicode.com
首页 > 其他好文 > 详细

FTP操作文件

时间:2015-03-11 19:49:14      阅读:1227      评论:0      收藏:0      [点我收藏+]

标签:ftp   ftp服务器   

package com.xxx.client;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;


import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.jfree.util.Log;


import com.xxx.group.pc.intf.Parameter;


/**
 * FTP连接
 * 
 * @author xxx  2015-03-11 
 */
public class FtpClientUtil {
private String server;
private String username;
private String password;
private FTPClient ftp;
private boolean binaryTransfer = false;


/**
* @param server
*            ftp服务器地址
* @param username
*            ftp服务器登陆用户
* @param password
*            ftp用户密码
*/
public FtpClientUtil(String server, String username, String password) {
this.server = server;
this.username = username;
this.password = password;
ftp = new FTPClient();
/*
* if(Configuration.PrintFTPCommandLog){ //打印FTP命令
* ftp.addProtocolCommandListener(new PrintCommandListener()); }
*/
}


public boolean connect() {
try {
int reply;
// 设置连接时间
ftp.setConnectTimeout(Parameter.FTP_TIME_OUT);

ftp.connect(server);  


// 连接后检测返回码来校验连接是否成功
reply = ftp.getReplyCode();


if (FTPReply.isPositiveCompletion(reply)) {
if (ftp.login(username, password)) {
// 设置为passive模式
ftp.enterLocalPassiveMode();
return true;
}
} else {
ftp.disconnect();
}
} catch (IOException e) {
System.err.println("FTP连接失败");
e.printStackTrace();
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException f) {
System.err.println("FTP关闭失败");
f.printStackTrace();
}
}
}
return false;
}


/**
* 下载一个文件到默认的本地路径中

* @param fileName
*            文件名称(不含路径)
* @param delFile
*            成功后是否删除该文件
* @return
*/
public boolean get(String fileName, boolean delFile) {
String remote = Parameter.FTP_REMOTE_DOWNPATH + fileName;
String local = Parameter.FTP_LOCAL_DOWNPATH + fileName;
return get(remote, local, delFile);
}


/**
* 上传一个文件到默认的远程路径中 提前定义好路径

* @param fileName
*            文件名称(不含路径)
* @param delFile
*            成功后是否删除该文件
* @return
*/
public boolean put(String fileName, boolean delFile, String remotePath) {
String remote = remotePath + fileName;
String local = Parameter.FTP_LOCAL_UPPATH + fileName;
return put(remote, local, delFile);
}


/**
* 遍历文件路径下的所有文件上传

* @param delFile
* @return
*/
public boolean[] putAll(boolean delFile) {
String remote = Parameter.FTP_REMOTE_UPPATH;
String local = Parameter.FTP_LOCAL_UPPATH;
return putAll(remote, local, delFile);
}


/**
* 上传多个文件到默认的远程路径中

* @param fileNames
*            文件名数组
* @param delFile
*            成功后是否删除文件
* @return
*/
public boolean[] put(String[] fileNames, boolean delFile, String remotePath) {
boolean[] result = new boolean[fileNames.length];
for (int j = 0; j < result.length; j++) {
result[j] = false;
}
String localFile;
for (int i = 0; i < fileNames.length; i++) {
localFile = fileNames[i];
result[i] = put(localFile, delFile, remotePath);
}
return result;
}


/**
* 上传多个文件到默认的远程路径中

* @param fileNames
*            文件名数组
* @param delFile
*            成功后是否删除文件
* @return
*/
public boolean[] putAll(String remoteAbsoluteFile,
String localAbsoluteFile, boolean delFile) {
String[] fileNames = {};
fileNames = FileUtil.refreshFileList(localAbsoluteFile);
boolean[] result = new boolean[fileNames.length];
for (int j = 0; j < result.length; j++) {
result[j] = false;
}
String localFile;
for (int i = 0; i < fileNames.length; i++) {
localFile = fileNames[i];
result[i] = put(localFile, delFile, remoteAbsoluteFile);
}
return result;
}


/**
* 上传一个本地文件到远程指定文件

* @param remoteAbsoluteFile
*            远程文件名(包括完整路径)
* @param localAbsoluteFile
*            本地文件名(包括完整路径)
* @return 成功时,返回true,失败返回false
*/
public boolean put(String remoteAbsoluteFile, String localAbsoluteFile,
boolean delFile) {
InputStream input = null;
try {
// //设置文件传输类型
if (binaryTransfer) {
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
} else {
ftp.setFileType(FTPClient.ASCII_FILE_TYPE);
}
// 处理传输
input = new FileInputStream(localAbsoluteFile);
ftp.storeFile(remoteAbsoluteFile, input);
if (delFile) {
File oldFile = new File(localAbsoluteFile);
if (oldFile.isFile() && oldFile.exists()) {
System.out.println("删除文件:" + localAbsoluteFile);
oldFile.delete();
}


(new File(localAbsoluteFile)).delete();
}
return true;
} catch (FileNotFoundException e) {
System.err.println("Local file not found:" + e.getMessage());
e.printStackTrace();
} catch (IOException e1) {
System.err.println("Could put file to server.");
e1.printStackTrace();
} finally {
try {
if (input != null) {
input.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}


return false;
}


/**
* 下载一个远程文件到本地的指定文件

* @param remoteAbsoluteFile
*            远程文件名(包括完整路径)
* @param localAbsoluteFile
*            本地文件名(包括完整路径)
* @return 成功时,返回true,失败返回false
*/
public boolean get(String remoteAbsoluteFile, String localAbsoluteFile,
boolean delFile) {
OutputStream output = null;
try {
// 设置文件传输类型
if (binaryTransfer) {
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
} else {
ftp.setFileType(FTPClient.ASCII_FILE_TYPE);
}
// 处理传输
output = new FileOutputStream(localAbsoluteFile);
ftp.retrieveFile(remoteAbsoluteFile, output);
output.close();
if (delFile) { // 删除远程文件
ftp.deleteFile(remoteAbsoluteFile);
}
return true;
} catch (FileNotFoundException e) {
System.err.println("Local file not found:" + e.getMessage());
} catch (IOException e1) {
System.err.println("Could put file to server.");
e1.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException e2) {
}
}
return false;
}


/**
* 列出远程目录下所有的文件

* @param remotePath
*            远程目录名
* @return 远程目录下所有文件名的列表,目录不存在或者目录下没有文件时返回0长度的数组
*/
public String[] listNames(String remotePath) {
String[] fileNames = null;
try {
FTPFile[] remotefiles = ftp.listFiles(remotePath);
fileNames = new String[remotefiles.length];
for (int i = 0; i < remotefiles.length; i++) {
fileNames[i] = remotefiles[i].getName();
}
} catch (IOException e) {
System.err.println("Could put file to server.");
e.printStackTrace();
}
return fileNames;
}


public void moveFilesByRename(String oldFilePath, String newFilePath)
throws Exception {
ftp.rename(oldFilePath, newFilePath);
ftp.deleteFile(oldFilePath);
}


/**
* 创建文件夹

* @param pathName
* @throws Exception
*/
public void makeDirectory(String pathName) throws Exception {
ftp.makeDirectory(pathName);
}


/**
* @param localPath
* @param remotePath
*            必须存在
* @param delFile
*/


// 原方法-xht
// public void putFolder(String localPath, String remotePath) throws
// Exception
// {
// System.out.println(">>>>>>>>>>>putFolder>>>>>>>>>");
// System.out.println("localPath:[" + localPath + "]");
// System.out.println("remotePath:[" + remotePath + "]");
// //跳转至工作目录
// ftp.changeWorkingDirectory(remotePath);
// File parentFolder = new File(localPath);
// ftp.makeDirectory(parentFolder.getName());
// String[] files = parentFolder.list();
// for (int i = 0; i < files.length; i++) {
// String childPath = parentFolder.getPath()+"/"+files[i];
// File file = new File(parentFolder.getPath()+"/"+files[i]);
// if(file.isDirectory()){
// putFolder(childPath, parentFolder.getName());
// ftp.changeToParentDirectory();
// }else{
// ftp.changeWorkingDirectory(parentFolder.getName());
// FileInputStream is = new FileInputStream(file);
// ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
// ftp.storeFile(file.getName(), is);
// is.close();
// }
// }
// }


// 上面为原方法,现在为更改影像目录所做更新-xht
public void putFolder(String localPath, String remotePath, String applyCode)throws Exception {
// 跳转至工作目录 如果工作目录为空,刚在此以年月创建。
if (null == remotePath || "".equals(remotePath)) {
String path = Parameter.CEBBANK_FTP_LOCAL_UPPATH;
ftp.changeWorkingDirectory(path);


String year = applyCode.substring(1, 5);
String month = applyCode.substring(5, 7);


ftp.makeDirectory(year);
ftp.changeWorkingDirectory(year);
ftp.makeDirectory(month);
ftp.changeWorkingDirectory(month);
} else {
ftp.changeWorkingDirectory(remotePath);
}
File parentFolder = new File(localPath);
ftp.makeDirectory(parentFolder.getName());
String[] files = parentFolder.list();
for (int i = 0; i < files.length; i++) {
String childPath = parentFolder.getPath() + "/" + files[i];
File file = new File(parentFolder.getPath() + "/" + files[i]);
if (file.isDirectory()) {
putFolder(childPath, parentFolder.getName(), applyCode);
ftp.changeToParentDirectory();
} else {
ftp.changeWorkingDirectory(parentFolder.getName());
FileInputStream is = new FileInputStream(file);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.storeFile(file.getName(), is);
is.close();
}
}
}


// 专为广发银行做的处理,有新加的银行此方法可能用   -xht 2014-02-27
public void putFoldernewCGB(String localPath, String remotePath,String applyCode) throws Exception
{
//跳转至工作目录 如果工作目录为空,刚在此以年月创建。
File remofile = new File(remotePath);
if(!remofile .exists()  && !remofile .isDirectory()){  
String path = Parameter.CGBBANK_FTP_LOCAL_UPPATH;
ftp.changeWorkingDirectory(path);
       String year = applyCode.substring(1,5);
       String month = applyCode.substring(5,7);
       ftp.makeDirectory(year);
       ftp.changeWorkingDirectory(year);
       ftp.makeDirectory(month);
       ftp.changeWorkingDirectory(month);    
}else{  
ftp.changeWorkingDirectory(remotePath);
}  
File parentFolder = new File(localPath);          
        ftp.makeDirectory(parentFolder.getName());
        
        //先将原有的文件删除
//        File reFolder = new File(remotePath);
//        String[] refiles = reFolder.list();
//        for (int j = 0; j < refiles.length; j++) {
//         File fe = new File(parentFolder.getPath()+"/"+refiles[j]);   
//         System.out.println("要删除的文件为:"+fe.getPath());
//         fe.delete();
//        }
        deleteFiles(remotePath);
        
        String[] files = parentFolder.list();
        for (int i = 0; i < files.length; i++) {   
        File file = new File(parentFolder.getPath()+"/"+files[i]);      
            if(file.isDirectory()){      
//             putFoldernew(childPath, parentFolder.getName(),applyCode);
//             ftp.changeToParentDirectory();
            continue;
            }else{
            ftp.changeWorkingDirectory(parentFolder.getName());
                FileInputStream is = new FileInputStream(file);
                ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftp.storeFile(file.getName(), is);      
                is.close();                            
            }    
        }     
}

public void deleteFiles(String path)
{
try
{
String[] names = ftp.listNames(path);
if(names != null && names.length > 0)
{
for(String name : names)
{
if(!ftp.deleteFile(name))
{
deleteFolder(name);
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}


public void deleteFolder(String path)
{
try
{
String[] names = ftp.listNames(path);
if (names != null && names.length > 0) {
for (String name : names) {
if (!ftp.deleteFile(name)) {
deleteFolder(name);
}
}
}


ftp.removeDirectory(path);
} catch (Exception e) {
e.printStackTrace();
}
}


/**
* 断开ftp连接
*/
public void disconnect() {
try {
ftp.logout();
if (ftp.isConnected()) {
ftp.disconnect();
}
} catch (IOException e) {
System.err.println("Could put file to server.");
e.printStackTrace();
}
}


/**
* @return Returns the binaryTransfer.
*/
public boolean isBinaryTransfer() {
return binaryTransfer;
}


/**
* @param binaryTransfer
*            The binaryTransfer to set.
*/
public void setBinaryTransfer(boolean binaryTransfer) {
this.binaryTransfer = binaryTransfer;
}

//add by qiaochangde 20141205 begin
/**
* 读取ftp目录下的文件,返回文件字符内容
* @param remoteFile
* @return
*/
public String readFile(String remoteFile){
String result = "";
InputStream ins = null;
try {
ins = ftp.retrieveFileStream(remoteFile);
BufferedReader reader=new BufferedReader(new InputStreamReader(ins)); 
        String line = "";
        StringBuffer sb = new StringBuffer();
        while((line =  reader.readLine()) != null) {
        sb.append(line);
        }
        result = sb.toString();
        reader.close();
        if(ins != null){
        ins.close();        
        }
        ftp.getReply();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

public void putFolderNJCB(String localPath, String remotePath, String applyCode)throws Exception {
// 跳转至工作目录 如果工作目录为空,刚在此以年月创建。
if (null == remotePath || "".equals(remotePath)) {
String path = Parameter.NJCBBANK_FTP_LOCAL_UPPATH;
ftp.changeWorkingDirectory(path);


String year = applyCode.substring(1, 5);
String month = applyCode.substring(5, 7);


ftp.makeDirectory(year);
ftp.changeWorkingDirectory(year);
ftp.makeDirectory(month);
ftp.changeWorkingDirectory(month);
} else {
ftp.changeWorkingDirectory(remotePath);
}
File parentFolder = new File(localPath);
ftp.makeDirectory(parentFolder.getName());
String[] files = parentFolder.list();
for (int i = 0; i < files.length; i++) {
String childPath = parentFolder.getPath() + "/" + files[i];
File file = new File(parentFolder.getPath() + "/" + files[i]);
if (file.isDirectory()) {
putFolderNJCB(childPath, parentFolder.getName(), applyCode);
ftp.changeToParentDirectory();
} else {
ftp.changeWorkingDirectory(parentFolder.getName());
FileInputStream is = new FileInputStream(file);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.storeFile(file.getName(), is);
is.close();
}
}
}

public String moveFolderForDownload(String localPath, String fileName) throws Exception {
String applyCode = fileName.substring(2,
fileName.lastIndexOf("."));
ftp.changeWorkingDirectory(localPath);


String year = applyCode.substring(1, 5);
String month = applyCode.substring(5, 7);
String day = applyCode.substring(7,9);


ftp.makeDirectory(year);
ftp.changeWorkingDirectory(year);
ftp.makeDirectory(month);
ftp.changeWorkingDirectory(month);
ftp.makeDirectory(day);
ftp.changeWorkingDirectory(day);

String newPath = localPath + year+"/"+month+"/"+day+"/" + fileName;

return newPath;
}

}

FTP操作文件

标签:ftp   ftp服务器   

原文地址:http://blog.csdn.net/wangyonglin1123/article/details/44201415

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!