ftp文件上传下载

一、ftp工具类:

package aa.bb;



import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.TimeZone;


import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
//import org.apache.log4j.Logger;


public class FtpUtil {
private FTPClient ftpClient;
private String strIp;
private int intPort;
private String user;
private String password;


//private static Logger logger = Logger.getLogger(FtpUtil.class.getName());

/**
* Ftp构造函数
* @param strIp
* @param intPort
* @param user
* @param Password
*/
public FtpUtil(String strIp, int intPort, String user, String Password) {
this.strIp = strIp;
this.intPort = intPort;
this.user = user;
this.password = Password;
this.ftpClient = new FTPClient();
}
/**
* @return 判断是否登入成功
* */
public boolean ftpLogin() {
boolean isLogin = false;
FTPClientConfig ftpClientConfig = new FTPClientConfig();
ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
this.ftpClient.setControlEncoding("GBK");
this.ftpClient.configure(ftpClientConfig);
try {
if (this.intPort > 0) {
this.ftpClient.connect(this.strIp, this.intPort);
} else {
this.ftpClient.connect(this.strIp);
}
// FTP服务器连接回答
int reply = this.ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
this.ftpClient.disconnect();
//logger.error("登录FTP服务失败!");
return isLogin;
}
this.ftpClient.login(this.user, this.password);
// 设置传输协议
this.ftpClient.enterLocalPassiveMode();
this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//logger.info(this.user + "成功登陆FTP服务器");
isLogin = true;
} catch (Exception e) {
e.printStackTrace();
//logger.error(this.user + "登录FTP服务失败!" + e.getMessage());
}
this.ftpClient.setBufferSize(1024 * 2);
this.ftpClient.setDataTimeout(30 * 1000);
return isLogin;
}


/**
* 关闭ftp连接
*/
public void ftpLogOut() {
if (null != this.ftpClient && this.ftpClient.isConnected()) {
try {
boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
if (reuslt) {
//logger.info("关闭FTP服务器连接");
}
} catch (IOException e) {
e.printStackTrace();
//logger.warn("退出FTP服务器异常!" + e.getMessage());
} finally {
try {
this.ftpClient.disconnect();// 关闭FTP服务器的连接
} catch (IOException e) {
e.printStackTrace();
//logger.warn("关闭FTP服务器的连接异常!");
}
}
}
}



/***
* 上传Ftp文件

* @param localFile
*            当地文件
* @param romotUpLoadePath上传服务器路径
*            - 应该以/结束
* */
public boolean uploadFile(File localFile, String romotUpLoadePath) {
BufferedInputStream inStream = null;
boolean success = false;
try {
this.ftpClient.changeWorkingDirectory("/");
String[] paths=romotUpLoadePath.split("/");
for (int i = 0; i < paths.length; i++) {
this.ftpClient.makeDirectory(paths[i]);
this.ftpClient.changeWorkingDirectory(paths[i]);
}


//this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改变工作路径
inStream = new BufferedInputStream(new FileInputStream(localFile));
//logger.info(localFile.getName() + "开始上传.....");
success = this.ftpClient.storeFile(localFile.getName(), inStream);

if (success == true) {
//logger.info(localFile.getName() + "上传成功");
this.ftpClient.changeWorkingDirectory("/");
return success;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
//logger.error(localFile + "未找到");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return success;
}


/***
* 下载文件

* @param remoteFileName
*            待下载文件名称
* @param localDires
*            下载到当地那个路径下
* @param remoteDownLoadPath
*            remoteFileName所在的路径
* */


public boolean downloadFile(String remoteFileName, String localDires,
String remoteDownLoadPath) {
String strFilePath = localDires + remoteFileName;
BufferedOutputStream outStream = null;
boolean success = false;
try {
this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
outStream = new BufferedOutputStream(new FileOutputStream(
strFilePath));
//logger.info(remoteFileName + "开始下载....");
success = this.ftpClient.retrieveFile(remoteFileName, outStream);
if (success == true) {
//logger.info(remoteFileName + "成功下载到" + strFilePath);
return success;
}
} catch (Exception e) {
e.printStackTrace();
//logger.error(remoteFileName + "下载失败");
} finally {
if (null != outStream) {
try {
outStream.flush();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (success == false) {
//logger.error(remoteFileName + "下载失败!!!");
}
return success;
}


/**
* 上传文件夹, Ftp 服务器路径 以目录"/"结束
*/

public boolean uploadDirectory(String localDirectory,
String remoteDirectoryPath) {
File src = new File(localDirectory);
try {
remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
this.ftpClient.makeDirectory(remoteDirectoryPath);
// ftpClient.listDirectories();
} catch (IOException e) {
e.printStackTrace();
System.out.println("目录创建失败");
//logger.info(remoteDirectoryPath + "目录创建失败");
}
File[] allFile = src.listFiles();
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
if (!allFile[currentFile].isDirectory()) {
String srcName = allFile[currentFile].getPath().toString();
uploadFile(new File(srcName), remoteDirectoryPath);
}
}
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
if (allFile[currentFile].isDirectory()) {
// 递归
uploadDirectory(allFile[currentFile].getPath().toString(),
remoteDirectoryPath);
}
}
return true;
}



/**
* 下载文件夹  远程文件夹
*/
public boolean downLoadDirectory(String localDirectoryPath,
String remoteDirectory) {
try {
String fileName = new File(remoteDirectory).getName();
localDirectoryPath = localDirectoryPath + fileName + "//";
new File(localDirectoryPath).mkdirs();
FTPFile[] allFile = this.ftpClient.listFiles(remoteDirectory);
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
if (!allFile[currentFile].isDirectory()) {
downloadFile(allFile[currentFile].getName(),
localDirectoryPath, remoteDirectory);
}
}
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
if (allFile[currentFile].isDirectory()) {
String strremoteDirectoryPath = remoteDirectory + "/"
+ allFile[currentFile].getName();
downLoadDirectory(localDirectoryPath,
strremoteDirectoryPath);
}
}
} catch (IOException e) {
e.printStackTrace();
//logger.info("下载文件夹失败");
return false;
}
return true;
}


// FtpClient的Set 和 Get 函数
public FTPClient getFtpClient() {
return ftpClient;
}


public void setFtpClient(FTPClient ftpClient) {
this.ftpClient = ftpClient;
}

}


二、测试调用:

FtpUtil ftp=new FtpUtil("192.168.110.126", 21, "test", "123456");
boolean brt=ftp.ftpLogin();
System.out.println("连接结果:"+brt);
boolean brt2=ftp.uploadFile(new File("E:\\入职培训\\开发培训\\培训文档\\4.开发规范.doc"), "开发目录/");
System.out.println("上传结果:"+brt2);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
'模板: Option Explicit Public Declare Function InternetOpen Lib "wininet.dll" Alias "InternetOpenA" _ (ByVal sAgent As String, ByVal LAccessType As Long, ByVal sProxyName As String, _ ByVal SProxyBypass As String, ByVal lFlags As Long) As Long Public Declare Function InternetConnect Lib "wininet.dll" Alias "InternetConnectA" _ (ByVal hInternetSession As Long, ByVal sServerName As String, _ ByVal nServerPort As Integer, ByVal sUsername As String, _ ByVal sPassword As String, ByVal lService As Long, _ ByVal lFlags As Long, ByVal lContext As Long) As Long Public Declare Function FtpGetFile Lib "wininet.dll" Alias "FtpGetFileA" _ (ByVal hFtpSession As Long, ByVal lpszRemoteFile As String, _ ByVal lpszNewFile As String, ByVal fFailIfExists As Boolean, _ ByVal dwFlagsAndAttributes As Long, ByVal dwFlags As Long, _ ByVal dwContext As Long) As Boolean Public Declare Function FtpPutFile Lib "wininet.dll" Alias "FtpPutFileA" _ (ByVal hFtpSession As Long, ByVal lpszLocalFile As String, _ ByVal lpszRemoteFile As String, ByVal dwFlags As Long, _ ByVal dwContext As Long) As Boolean Public Declare Function FtpDeleteFile Lib "wininet.dll" Alias "FtpDeleteFileA" _ (ByVal hFtpSession As Long, ByVal lpszFileName As String) As Boolean Public Declare Function FtpRenameFile Lib "wininet.dll" Alias "FtpRenameFileA" _ (ByVal hFtpSession As Long, ByVal lpszExsiting As String, ByVal lpszNew As String) As Boolean Public Declare Function InternetCloseHandle Lib "wininet.dll" (ByVal hInet As Long) As Integer Public Declare Function FtpFindFirstFile Lib "wininet.dll" Alias "FtpFindFirstFileA" _ (ByVal hFtpSession As Long, ByVal lpszSearchFile As String, _ lpFindFileData As WIN32_FIND_DATA, ByVal dwFlags As Long, _ ByVal dwContent As Long) As Long Public Declare Function InternetFindNextFile Lib "wininet.dll" Alias "InternetFindNextFileA" _ (ByVal hFind As Long, lpvFndData As WIN32_FIND_DATA) As Long Public Type FILETIME dwLowDateTime As Long dwHighDateTime As Long End Type Public Type WIN32_FIND_DATA dwFilAttributes As Long ftCreationTime As FILETIME ftLastAccessTime As FILETIME ftLastWriteTime As FILETIME nFileSizeHigh As Long nFileSizeLow As Long dwReserved0 As Long dwReserved1 As Long cFileName As String * 260 cAlternate As String * 14 End Type Public Declare Function GetOpenFileName Lib "comdlg32.dll" Alias _ "GetOpenFileNameA" (pOpenfilename As OPENFILENAME) As Long Type OPENFILENAME lStructSize As Long hwndOwner As Long hInstance As Long lpstrFilter As String lpstrCustomFilter As String nMaxCustFilter As Long nFilterIndex As Long lpstrFile As String nMaxFile As Long lpstrFileTitle As String nMaxFileTitle As Long lpstrInitialDir As String lpstrTitle As String flags As Long nFileOffset As Integer nFileExtension As Integer lpstrDefExt As String lCustData As Long lpfnHook As Long lpTemplateName As String End Type '窗体: Private Sub Command1_Click() 'FTP下载 lnginet = InternetOpen(vbNullString, INTERNET_OPEN_TYPE_PRECONFIG, _ vbNullString, vbNullString, 0&) If lnginet Then lnginetconn = InternetConnect(lnginet, "219.131.192.243", 0, _ "posui", "djposui", 1, 0, 0) If lnginetconn Then blnRC = FtpGetFile(lnginetconn, "/load.txt", "c:\load.txt", 0, 0, 1, 0) If blnRC Then MsgBox "download ok!!!" End If InternetCloseHandle lnginetconn InternetCloseHandle lnginet MsgBox "close ok!!!" Else MsgBox "can't connect" End If Else MsgBox "ftp wrong" End If End Sub Private Sub Command2_Click() 'FTP上传 lnginet = InternetOpen(vbNullString, INTERNET_OPEN_TYPE_PRECONFIG, _ vbNullString, vbNullString, 0&) If lnginet Then lnginetconn = InternetConnect(lnginet, "219.131.192.243", 0, _ "administrator", "vai8888", 1, 0, 0) If lnginetconn Then blnRC = FtpPutFile(lnginetconn, "c:\1.txt", "/1.txt", 0, 0) If blnRC Then MsgBox "download ok!!!" End If InternetCloseHandle lnginetconn InternetCloseHandle lnginet MsgBox "close ok!!!" Else MsgBox "can't connect" End If Else MsgBox "ftp wrong" End If End Sub 方法2: '部件INET Private Sub Command1_Click() Me.Inet1.Execute Me.Inet1.URL, "send c:\11.txt /1.txt" '保存 End Sub Private Sub Command2_Click() Me.Inet1.Execute Me.Inet1.URL, "get /2.txt c:\2.txt" '下载 End Sub

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值