java使用Apache工具集實現(xiàn)ftp文件傳輸代碼詳解
本文主要介紹如何使用Apache工具集commons-net提供的ftp工具實現(xiàn)向ftp服務器上傳和下載文件。
一、準備
需要引用commons-net-3.5.jar包。
使用maven導入:
<dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.5</version> </dependency>
手動下載:
http://www.dbjr.com.cn/softs/550085.html
二、連接FTP Server
/**
* 連接FTP Server
* @throws IOException
*/
public static final String ANONYMOUS_USER="anonymous";
private FTPClient connect(){
FTPClient client = new FTPClient();
try{
//連接FTP Server
client.connect(this.host, this.port);
//登陸
if(this.user==null||"".equals(this.user)){
//使用匿名登陸
client.login(ANONYMOUS_USER, ANONYMOUS_USER);
} else{
client.login(this.user, this.password);
}
//設置文件格式
client.setFileType(FTPClient.BINARY_FILE_TYPE);
//獲取FTP Server 應答
int reply = client.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){
client.disconnect();
return null;
}
//切換工作目錄
changeWorkingDirectory(client);
System.out.println("===連接到FTP:"+host+":"+port);
}
catch(IOException e){
return null;
}
return client;
}
/**
* 切換工作目錄,遠程目錄不存在時,創(chuàng)建目錄
* @param client
* @throws IOException
*/
private void changeWorkingDirectory(FTPClient client) throws IOException{
if(this.ftpPath!=null&&!"".equals(this.ftpPath)){
Boolean ok = client.changeWorkingDirectory(this.ftpPath);
if(!ok){
//ftpPath 不存在,手動創(chuàng)建目錄
StringTokenizer token = new StringTokenizer(this.ftpPath,"\\//");
while(token.hasMoreTokens()){
String path = token.nextToken();
client.makeDirectory(path);
client.changeWorkingDirectory(path);
}
}
}
}
/**
* 斷開FTP連接
* @param ftpClient
* @throws IOException
*/
public void close(FTPClient ftpClient) throws IOException{
if(ftpClient!=null && ftpClient.isConnected()){
ftpClient.logout();
ftpClient.disconnect();
}
System.out.println("!!!斷開FTP連接:"+host+":"+port);
}
host:ftp服務器ip地址
port:ftp服務器端口
user:登陸用戶
password:登陸密碼
登陸用戶為空時,使用匿名用戶登陸。
ftpPath:ftp路徑,ftp路徑不存在時自動創(chuàng)建,如果是多層目錄結構,需要迭代創(chuàng)建目錄。
三、上傳文件
/**
* 上傳文件
* @param targetName 上傳到ftp文件名
* @param localFile 本地文件路徑
* @return
*/
public Boolean upload(String targetName,String localFile){
//連接ftp server
FTPClient ftpClient = connect();
if(ftpClient==null){
System.out.println("連接FTP服務器["+host+":"+port+"]失?。?);
return false;
}
File file = new File(localFile);
//設置上傳后文件名
if(targetName==null||"".equals(targetName))
targetName = file.getName();
FileInputStream fis = null;
try{
long now = System.currentTimeMillis();
//開始上傳文件
fis = new FileInputStream(file);
System.out.println(">>>開始上傳文件:"+file.getName());
Boolean ok = ftpClient.storeFile(targetName, fis);
if(ok){
//上傳成功
long times = System.currentTimeMillis() - now;
System.out.println(String.format(">>>上傳成功:大?。?s,上傳時間:%d秒", formatSize(file.length()),times/1000));
} else//上傳失敗
System.out.println(String.format(">>>上傳失敗:大?。?s", formatSize(file.length())));
}
catch(IOException e){
System.err.println(String.format(">>>上傳失?。捍笮。?s", formatSize(file.length())));
e.printStackTrace();
return false;
}
finally{
try{
if(fis!=null)
fis.close();
close(ftpClient);
}
catch(Exception e){
}
}
return true;
}
四、下載文件
/**
* 下載文件
* @param localPath 本地存放路徑
* @return
*/
public int download(String localPath){
// 連接ftp server
FTPClient ftpClient = connect();
if(ftpClient==null){
System.out.println("連接FTP服務器["+host+":"+port+"]失??!");
return 0;
}
File dir = new File(localPath);
if(!dir.exists())
dir.mkdirs();
FTPFile[] ftpFiles = null;
try{
ftpFiles = ftpClient.listFiles();
if(ftpFiles==null||ftpFiles.length==0)
return 0;
}
catch(IOException e){
return 0;
}
int c = 0;
for (int i=0;i<ftpFiles.length;i++){
FileOutputStream fos = null;
try{
String name = ftpFiles[i].getName();
fos = new FileOutputStream(new File(dir.getAbsolutePath()+File.separator+name));
System.out.println("<<<開始下載文件:"+name);
long now = System.currentTimeMillis();
Boolean ok = ftpClient.retrieveFile(new String(name.getBytes("UTF-8"),"ISO-8859-1"), fos);
if(ok){
//下載成功
long times = System.currentTimeMillis() - now;
System.out.println(String.format("<<<下載成功:大?。?s,上傳時間:%d秒", formatSize(ftpFiles[i].getSize()),times/1000));
c++;
} else{
System.out.println("<<<下載失敗");
}
}
catch(IOException e){
System.err.println("<<<下載失敗");
e.printStackTrace();
}
finally{
try{
if(fos!=null)
fos.close();
close(ftpClient);
}
catch(Exception e){
}
}
}
return c;
}
格式化文件大小
private static final DecimalFormat DF = new DecimalFormat("#.##");
/**
* 格式化文件大小(B,KB,MB,GB)
* @param size
* @return
*/
private String formatSize(long size){
if(size<1024){
return size + " B";
}else if(size<1024*1024){
return size/1024 + " KB";
}else if(size<1024*1024*1024){
return (size/(1024*1024)) + " MB";
}else{
double gb = size/(1024*1024*1024);
return DF.format(gb)+" GB";
}
}
五、測試
public static void main(String args[]){
FTPTest ftp = new FTPTest("192.168.1.10",21,null,null,"/temp/2016/12");
ftp.upload("newFile.rar", "D:/ftp/TeamViewerPortable.rar");
System.out.println("");
ftp.download("D:/ftp/");
}
結果
===連接到FTP:192.168.1.10:21 >>>開始上傳文件:TeamViewerPortable.rar >>>上傳成功:大?。? MB,上傳時間:3秒 !!!斷開FTP連接:192.168.1.10:21 ===連接到FTP:192.168.1.10:21 <<<開始下載文件:newFile.rar <<<下載成功:大?。? MB,上傳時間:4秒 !!!斷開FTP連接:192.168.1.10:21
總結
以上就是本文關于java使用Apache工具集實現(xiàn)ftp文件傳輸代碼詳解的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關文章
Java8中 LocalDate和java.sql.Date的相互轉換操作
這篇文章主要介紹了Java8中 LocalDate和java.sql.Date的相互轉換操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12
java面試LruCache?和?LinkedHashMap及算法實現(xiàn)
這篇文章主要為大家介紹了java面試LruCache?和?LinkedHashMap及算法實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02
Spring Boot + Mybatis多數(shù)據(jù)源和動態(tài)數(shù)據(jù)源配置方法
最近做項目遇到這樣的應用場景,項目需要同時連接兩個不同的數(shù)據(jù)庫A, B,并且它們都為主從架構,一臺寫庫,多臺讀庫。下面小編給大家?guī)砹薙pring Boot + Mybatis多數(shù)據(jù)源和動態(tài)數(shù)據(jù)源配置方法,需要的朋友參考下吧2018-01-01

