ftp上传,下载,删除文件
直接看最下面的main()方法中的代码,复制全部代码,输入自己的ftp路径和用户信息。
package com.sinosoft.lis.ybt.bl;
import ind.crf.free.ftp.FTP;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.util.Calendar;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import com.sinosoft.utility.CError;
public class TestFtp {
public FTPClient ftpClient = null;
public FTP ftp = null;
private String Host = null; // ftp 主机Host
private String UserName = null;
private String Password = null;
private int Port = 21;
public TestFtp()
{
System.out.println("begin");
}
/**
* 初始化
* @param ip FTP服务器地址
* @param user 服务名
* @param password 密码
* @param port 端口号
*/
public TestFtp(String host,String username,String password,int port)
{
this.Host= host;
this.UserName= username;
this.Password=password;
this.Port= port;
}
/**
* 创建FTP连接
*/
public boolean connectServer() {
boolean flag = true;
ftpClient = new FTPClient();
int reply;
try {
ftpClient.connect(Host);
ftpClient.login(UserName, Password);
System.out.print(ftpClient.getReplyString());
reply = ftpClient.getReplyCode();
// 将文件传输类型设置为二进制
System.out.println("FTPClient.ASCII_FILE_TYPE:"+FTPClient.ASCII_FILE_TYPE);
ftpClient.setFileTransferMode(FTPClient.ASCII_FILE_TYPE);
System.out.println("END:ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE)");
//防止server超时断开
ftpClient.setDataTimeout(120000);
if (!FTPReply.isPositiveCompletion(reply)){
ftpClient.disconnect();
System.out.println("FALSE: FTPReply.isPositiveCompletion(reply)");
System.err.println("FTP server refused connection.");
flag = false;
}
System.out.println("END: connectServer()");
}catch (SocketException e){
flag = false;
e.printStackTrace();
System.err.println("登录ftp服务器 " + Host + " 失败,连接超时!");
}catch (IOException e){
flag = false;
e.printStackTrace();
System.err.println("登录ftp服务器 " + Host + " 失败,FTP服务器无法打开!");
}catch(Exception e){
flag = false;
e.printStackTrace();
System.err.println("登录ftp服务器 " + Host + " 失败,原因未知!");
}
System.out.println("登陆ftp服务器成功"+Host);
return flag;
}
/**
* 关闭连接
*/
private void closeConnect() {
try {
if (ftpClient != null) {
ftpClient.disconnect();
}
//ftpClient = null;
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除ftp上的文件
* @param srcFname 相对路径
* @return
*/
public int removeFile(String srcFname){
int flag = 0;
if( ftpClient!=null ){
try {
flag = ftpClient.dele(srcFname);
System.out.println("removeFile()返回值:"+flag);//测试删除成功返回250,失败返回550
} catch (IOException e) {
flag = 0;
e.printStackTrace();
this.closeConnect();
}
}
return flag;
}
/**
* 删除ftp上的空文件夹
* @param srcFname 相对路径
* @return
*/
public boolean deleteDirectory(String srcFname){
boolean flag = true;
if( ftpClient!=null ){
try {
flag= ftpClient.removeDirectory(srcFname);
System.out.println("removeDirectory() 返回值:"+flag);
} catch (IOException e) {
flag = false;
e.printStackTrace();
this.closeConnect();
}
}
return flag;
}
/**
* 重命名ftp上的文件
* @param oldFileName 旧名字
* @param newFileName 新旧名字
* @return
*/
public boolean renameFile(String oldFileName,String newFileName) {
boolean flag = true;
try {
flag = ftpClient.rename(oldFileName, newFileName);
System.out.println("重命名!!"+flag);
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* ftp上的创建文件夹
* @param dirname 名字
* @return
*/
public boolean createDir(String dirname){
boolean flag = true;
try{
flag = ftpClient.makeDirectory(dirname);
System.out.println(flag+" 在目标服务器上成功建立了文件夹: " + dirname);
}catch(Exception ex){
System.out.println(ex.getMessage());
}
return flag;
}
/**
* 参数说明:
* localStr:本地目录+文件名,都用绝对路径
* remoteStr = 远程目录+文件名,如果要取的文件直接在登陆后的默认目录下,这里远程目录可以不要 remoteStr = /文件名;
*/
public boolean ApacheFTPDownFile(String localStr, String remoteStr)
{
try {
FileOutputStream fos = null;
Calendar cCalendar = Calendar.getInstance();
long currTime = cCalendar.getTimeInMillis();
if(connectServer()){
/*得到相应的目录和远程文件*/
int i =0;
// i = remoteStr.lastIndexOf(File.separator);
i = remoteStr.lastIndexOf("/");
String currDir = remoteStr.substring(0, i);
String Remotefile = remoteStr.substring(i + 1);
if (remoteStr.equals("")) {
System.out.println("请输入正确的文件名!");
return false;
}
if(!checkRemoteFile(currDir,Remotefile)){
return false;
}
// 若本地路径不存在则生成路径
if(!checkLocalDir(localStr)){
return false;
}
//下载文件到本地
File file = null;
file = new File(localStr);
fos = new FileOutputStream(file);
ftpClient.retrieveFile(Remotefile, fos);
System.out.println(ftpClient.getReplyString());
fos.flush();
fos.close();
closeConnect();
cCalendar = Calendar.getInstance();
long currTime2 = cCalendar.getTimeInMillis();
long diff2 = currTime2 - currTime;
System.out.println("所用时间为=" + diff2);
}
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("下载文件失败!!!!");
return false;
}
return true;
}
private boolean checkLocalDir(String localStr )
{
System.out.println("!!!!!:"+localStr);
File formatPath = null;
//int j = localStr.lastIndexOf("\\");
int j = localStr.lastIndexOf("//");
String localDir = localStr.substring(0, j);
formatPath = new File(localDir);
if (!formatPath.exists()) {
formatPath.mkdirs();
}
// TODO Auto-generated method stub
return true;
}
private boolean checkLocalDir1(String localStr )
{
File formatPath = null;
int j = localStr.lastIndexOf("/");
String localDir = localStr.substring(0, j);
formatPath = new File(localDir);
if (!formatPath.exists()) {
formatPath.mkdirs();
}
// TODO Auto-generated method stub
return true;
}
/*
* 对远程文件进行分析
* */
private boolean checkRemoteFile(String cFileDir,String cFileName)
{
try{
boolean tFlag = false;
System.out.println("1111111:"+cFileDir);
System.out.println("2222222:"+cFileName);
tFlag = ftpClient.changeWorkingDirectory(cFileDir);
if (!tFlag) {
System.out.println("路径出错");
CError tError = new CError();
tError.moduleName = "ApacheFTP";
tError.functionName = "dealData";
tError.errorMessage = "请检查:[" + cFileDir + "]路径是否正确";
return false;
}
System.out.println(ftpClient.printWorkingDirectory());
System.out.println(ftpClient.getReplyString());
FTPFile ff[] = ftpClient.listFiles();
boolean fileExist = false;
if (ff == null || ff.length == 0) {
System.out.println("该目录下无任何文件!");
return false;
} else {
System.out.println("该目录下有文件!length:"+ff.length);
for(int j = 0;j<ff.length;j++){
if(ff[j].getName().equals(cFileName)){
System.out.println("在FTP目录上找到了文件!");
fileExist = true;
break;
}
}
}
if(!fileExist){
System.out.println("在FTP目录下没有读取到文件");
return false;
}
return true;
}
catch (Exception ex) {
ex.printStackTrace();
try {
if (ftpClient != null) {
ftpClient.disconnect();
}
} catch (Exception e) {
}
return false;
}
}
/**
* 获取文件
*
* @param localStr
* 本地文件全路径名
* @param remoteStr
* 远程文件全路径名
*/
public boolean FTPGetFile(String localStr, String remoteStr, String address,
String user, String pass)
{
Host = address;
UserName = user;
Password = pass;
Port = 21;
if (!ftpLogin()) {
System.out.println("FTP登陆失败,Host:" + Host + " Port:" + Port
+ " UserName:" + UserName + " Password:" + Password);
return false;
}
System.out.println("下载文件:" + localStr + "," + remoteStr);
String Remotefile = "";
String currDir = "";
int i = 0;
ftp.setTransfer(FTP.TRANSFER_PASV);
ftp.setMode(FTP.MODE_AUTO);
/* 对远程文件进行分析 */
if (remoteStr.equals("")) {
System.out.println("请输入正确的文件名!");
return false;
}
/* 得到相应的目录和远程文件 */
i = remoteStr.lastIndexOf("/");
currDir = remoteStr.substring(0, i);
Remotefile = remoteStr.substring(i + 1);
System.out.println("CurrDir is :" + currDir);
System.out.println("FileName is :" + Remotefile);
ftp.cd(currDir);
System.out.print(ftp.lastReply());
System.out.println("FTP.CODE_TRANSFER_OK:" + FTP.CODE_TRANSFER_OK);
System.out.println("ftp.lastCode()111:" + ftp.lastCode());
if (ftp.lastCode() != FTP.CODE_CD_OK) {
System.out.println("the remote directory does not exist.");
ftp.disconnect();
return false;
}
/**
* 没有路径生成路径
*/
// int j = localStr.lastIndexOf("\\");
int j = localStr.lastIndexOf("//");
String localDir = localStr.substring(0, j);
File file = new File(localDir);
if (!file.exists()) {
System.out.println("the local directory does not exist.");
file.mkdirs();
}
System.out.println("ftp.lastCode()222:" + ftp.lastCode());
ftp.download(Remotefile, localStr);
System.out.println(ftp.lastReply());
System.out.println("ftp.lastCode()333:" + ftp.lastCode());
if (ftp.lastCode() != FTP.CODE_TRANSFER_OK) {
System.out.println("error while downloading");
ftp.disconnect();
File f = new File(localStr);
long taille = f.length();
System.out.println("taille:::"+taille);
ftpLogin();
ftp.cd(currDir);
long rollback = 512;
ftp.download(Remotefile, localStr, taille - rollback);
}
ftp.disconnect();
return true;
}
public boolean ftpLogin()
{
ftp = new FTP(Host, Port);
ftp.connect();
System.out.print(ftp.lastReply());
if (ftp.lastCode() != FTP.CODE_CONNECT_OK) {
System.out.println("Connection failed.");
return false;
}
ftp.login(UserName, Password);
System.out.print(ftp.lastReply());
if (ftp.lastCode() != FTP.CODE_LOGGEDIN) {
ftp.disconnect();
return false;
}
return true;
}
public void upFile(String path, String filename, String localFilePath)
{
try {
this.connectServer();
FileInputStream in=new FileInputStream(new File(localFilePath));
ftpClient.changeWorkingDirectory(path);
ftpClient.storeFile(filename, in);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 上传文件
* @param file 文件
* @param path 上传服务器路径
* @return
*/
public boolean ApacheFTPUploadFile(File file,String path){
try
{
if (!file.isFile()) {
//不是文件
return false;
}else if(!fileSize(file)){
//控制文件大小
return false;
}
if (!connectServer()) {
return false;
}
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//转到path路径
//path=this.pathAddress(path);
ftpClient.makeDirectory(path);
//进入服务器目录
if(!ftpClient.changeWorkingDirectory(path)){
System.out.println("上载路径出错");
return false;
}
//给文件加上时间撮,防止服务器文件重复
String fileName=file.getName();
/*
* sl add 2008年12月27日22:53:25
* 加上时间撮是合理的,但邮储要求文件格式必须要满足他们的要求
* 可以跟他们沟通让他们的格式要求中增加时间撮,我们的程序就不主动给它添加时间撮了
* 这里先注掉它!
*/
// int lastIndex=fileName.lastIndexOf(".");
// fileName=fileName.substring(0,lastIndex)+"_"+System.currentTimeMillis()+fileName.substring(lastIndex);
FileInputStream fis=null;
try {
fis=new FileInputStream(file);
if(!ftpClient.storeFile(fileName, fis)){
closeConnect();
return false;
}
// closeConnect();
// fis.close();
// String strOldName = file.getPath();
// String strNewName ="";
// if(file.getName().indexOf(".des")>=0)
// {
// strNewName = strOldName.substring(0, strOldName.length() - 8)
// + ".dat";
// }
// else
// {
// strNewName = strOldName.substring(0, strOldName.length() - 4)
// + ".dat";
// }
// File fileNew = new File(strNewName);
//
// if (fileNew.exists()) {
// fileNew.delete();
// }
// //file.
// if (!file.renameTo(fileNew)) {
// return false;
// }
} catch (IOException e) {
e.printStackTrace();
return false;
}finally{
if (fis != null) {
fis.close();
}
closeConnect();
}
}
catch(IOException e){
e.printStackTrace();
return false;
}
return true;
}
/**
* 控制文件的大小,默认为5M
* @param file_in 文件
*/
private boolean fileSize(File file_in) {
return this.fileSize(file_in,5);
}
/**
* 控制文件的大小
* @param file_in 文件
* @param size 文件大小,单位为M
*/
private boolean fileSize(File file_in,int size) {
if (file_in == null || file_in.length() == 0) {
//文件为空
return false;
} else {
if (file_in.length() > (1024 * 1024 * size)){
//文件大小不能大与size
return false;
}
}
return true;
}
/**
* 格式化文件路径 检查path最后有没有分隔符'\'
* @param path
* @return
*/
public String pathAddress(String path){
if (path==null || path.length()<1) {
return "";
}
String temp_path=path.substring(path.length()-1);
if (!temp_path.equals("/") && !temp_path.equals("\\")) {
temp_path=path+File.separator;
}else{
temp_path=path;
}
return temp_path;
}
//add by
public boolean getAndUpFile(String downLoadFileName,String upLoadFileName){
String path = "\\bea\\ui\\temp\\pabcvideocache\\";
File exeFile1 = new File(path);
if(!exeFile1.exists()){
boolean bo = exeFile1.mkdir();
System.out.println(bo+"创建文件夹"+exeFile1);
}
String cache_filePath = path+upLoadFileName.substring(upLoadFileName.lastIndexOf("/")+1);
System.out.println("getAndUpFile:\t"+cache_filePath);
FTPGetFile(cache_filePath,downLoadFileName,Host,UserName,Password);
upFile(upLoadFileName.substring(0,upLoadFileName.lastIndexOf("/")),upLoadFileName.substring(upLoadFileName.lastIndexOf("/")+1),cache_filePath);
File file = new File(cache_filePath);
file.delete();
return true;
}
public String getHost() {
return Host;
}
public void setHost(String cHost) {
Host = cHost;
}
public String getUser() {
return UserName;
}
public void setUser(String user) {
UserName = user;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public int getPort() {
return Port;
}
public void setPort(int port) {
Port = port;
}
public static void main(String[] args) {
String ip="输入ftp地址";
String user="输入用户名r";
String password="输入密码";
int port=21;
TestFtp tTestFtp = new TestFtp(ip,user,password,port);
File file = new File("E://001/上传文件.zip");
//上传文件
tTestFtp.ApacheFTPUploadFile(file, "/u01/fileZip/zip/bocFTP/");
//下载文件 例如:/u01/fileZip/zip/bocFTP/3123213.txt
tTestFtp.ApacheFTPDownFile("E://003/555.txt","输入ftp文件的路径带着要下载文件的名字");
//另一个下载文件
tTestFtp.FTPGetFile("E://003/ff.txt", "输入ftp文件的路径带着要下载文件的名字", "输入ftp地址", "输入用户名", "输入密码");
}
}