Spring FTP上傳下載工具類遇到問(wèn)題小結(jié)
前言
最近在項(xiàng)目中需要和ftp服務(wù)器進(jìn)行交互,在網(wǎng)上找了一下關(guān)于ftp上傳下載的工具類,大致有兩種。
第一種是單例模式的類。
第二種是另外定義一個(gè)Service,直接通過(guò)Service來(lái)實(shí)現(xiàn)ftp的上傳下載。
這兩種感覺(jué)都有利弊。
第一種實(shí)現(xiàn)了代碼復(fù)用,但是配置信息全需要寫(xiě)在類中,維護(hù)比較復(fù)雜。
第二種如果是spring框架,可以通過(guò)propertis文件,動(dòng)態(tài)的注入配置信息,但是又不能代碼復(fù)用。
所以我打算自己實(shí)現(xiàn)一個(gè)工具類,來(lái)把上面的兩種優(yōu)點(diǎn)進(jìn)行整合。順便把一些上傳過(guò)程中一些常見(jiàn)的問(wèn)題也給解決了。
因?yàn)槲沂褂玫氖莝pring框架,如果把工具類聲明為bean給spring管理,他默認(rèn)就是單例的,所以不需要我再實(shí)現(xiàn)單例。并且因?yàn)槭莃ean,所以我可以把properties文件的屬性注入bean的屬性中,實(shí)現(xiàn)解耦,下面是具體代碼:
package com.cky.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//使用spring自動(dòng)生成單例對(duì)象,
//@Component
public class FtpUtil {
//通過(guò)properties文件自動(dòng)注入
@Value("${ftp.host}")
private String host; //ftp服務(wù)器ip
@Value("${ftp.port}")
private int port; //ftp服務(wù)器端口
@Value("${ftp.username}")
private String username;//用戶名
@Value("${ftp.password}")
private String password;//密碼
@Value("${ftp.basePath}")
private String basePath;//存放文件的基本路徑
//測(cè)試的時(shí)候把這個(gè)構(gòu)造函數(shù)打開(kāi),設(shè)置你的初始值,然后在代碼后面的main方法運(yùn)行測(cè)試
/*public FtpUtil() {
//System.out.println(this.toString());
host="192.168.100.77";
port=21;
username="ftpuser";
password="ftp54321";
basePath="/home/ftpuser/";
}*/
/**
*
* @param path 上傳文件存放在服務(wù)器的路徑
* @param filename 上傳文件名
* @param input 輸入流
* @return
*/
public boolean fileUpload(String path,String filename,InputStream input) {
FTPClient ftp=new FTPClient();
try {
ftp.connect(host, port);
ftp.login(username, password);
//設(shè)置文件編碼格式
ftp.setControlEncoding("UTF-8");
//ftp通信有兩種模式
//PORT(主動(dòng)模式)客戶端開(kāi)通一個(gè)新端口(>1024)并通過(guò)這個(gè)端口發(fā)送命令或傳輸數(shù)據(jù),期間服務(wù)端只使用他開(kāi)通的一個(gè)端口,例如21
//PASV(被動(dòng)模式)客戶端向服務(wù)端發(fā)送一個(gè)PASV命令,服務(wù)端開(kāi)啟一個(gè)新端口(>1024),并使用這個(gè)端口與客戶端的21端口傳輸數(shù)據(jù)
//由于客戶端不可控,防火墻等原因,所以需要由服務(wù)端開(kāi)啟端口,需要設(shè)置被動(dòng)模式
ftp.enterLocalPassiveMode();
//設(shè)置傳輸方式為流方式
ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
//獲取狀態(tài)碼,判斷是否連接成功
if(!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
throw new RuntimeException("FTP服務(wù)器拒絕連接");
}
//轉(zhuǎn)到上傳文件的根目錄
if(!ftp.changeWorkingDirectory(basePath)) {
throw new RuntimeException("根目錄不存在,需要?jiǎng)?chuàng)建");
}
//判斷是否存在目錄
if(!ftp.changeWorkingDirectory(path)) {
String[] dirs=path.split("/");
//創(chuàng)建目錄
for (String dir : dirs) {
if(null==dir||"".equals(dir)) continue;
//判斷是否存在目錄
if(!ftp.changeWorkingDirectory(dir)) {
//不存在則創(chuàng)建
if(!ftp.makeDirectory(dir)) {
throw new RuntimeException("子目錄創(chuàng)建失敗");
}
//進(jìn)入新創(chuàng)建的目錄
ftp.changeWorkingDirectory(dir);
}
}
//設(shè)置上傳文件的類型為二進(jìn)制類型
ftp.setFileType(FTP.BINARY_FILE_TYPE);
//上傳文件
if(!ftp.storeFile(filename, input)) {
return false;
}
input.close();
ftp.logout();
return true;
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
if(ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
return false;
}
/**
*
* @param filename 文件名,注意!此處文件名為加路徑文件名,如:/2015/06/04/aa.jpg
* @param localPath 存放到本地第地址
* @return
*/
public boolean downloadFile(String filename,String localPath) {
FTPClient ftp=new FTPClient();
try {
ftp.connect(host, port);
ftp.login(username, password);
//設(shè)置文件編碼格式
ftp.setControlEncoding("UTF-8");
//ftp通信有兩種模式
//PORT(主動(dòng)模式)客戶端開(kāi)通一個(gè)新端口(>1024)并通過(guò)這個(gè)端口發(fā)送命令或傳輸數(shù)據(jù),期間服務(wù)端只使用他開(kāi)通的一個(gè)端口,例如21
//PASV(被動(dòng)模式)客戶端向服務(wù)端發(fā)送一個(gè)PASV命令,服務(wù)端開(kāi)啟一個(gè)新端口(>1024),并使用這個(gè)端口與客戶端的21端口傳輸數(shù)據(jù)
//由于客戶端不可控,防火墻等原因,所以需要由服務(wù)端開(kāi)啟端口,需要設(shè)置被動(dòng)模式
ftp.enterLocalPassiveMode();
//設(shè)置傳輸方式為流方式
ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
//獲取狀態(tài)碼,判斷是否連接成功
if(!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
throw new RuntimeException("FTP服務(wù)器拒絕連接");
}
int index=filename.lastIndexOf("/");
//獲取文件的路徑
String path=filename.substring(0, index);
//獲取文件名
String name=filename.substring(index+1);
//判斷是否存在目錄
if(!ftp.changeWorkingDirectory(basePath+path)) {
throw new RuntimeException("文件路徑不存在:"+basePath+path);
}
//獲取該目錄所有文件
FTPFile[] files=ftp.listFiles();
for (FTPFile file : files) {
//判斷是否有目標(biāo)文件
//System.out.println("文件名"+file.getName()+"---"+name);
if(file.getName().equals(name)) {
//System.out.println("找到文件");
//如果找到,將目標(biāo)文件復(fù)制到本地
File localFile =new File(localPath+"/"+file.getName());
OutputStream out=new FileOutputStream(localFile);
ftp.retrieveFile(file.getName(), out);
out.close();
}
}
ftp.logout();
return true;
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
if(ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
//兩個(gè)功能其中一個(gè)使用的話另一個(gè)需要注釋
public static void main(String []args) {
//上傳測(cè)試-----------------------------------
/*FileInputStream in;
try {
in=new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\json.png"));
FtpUtil ftputil=new FtpUtil();
boolean flag=ftputil.fileUpload("/2015/06/04", "aa.jpg", in);
System.out.println(flag);
}catch (Exception e) {
e.printStackTrace();
}finally {
}*/
//下載測(cè)試--------------------------------------
String filename="/2015/06/04/aa.jpg";
String localPath="F:\\";
FtpUtil ftputil=new FtpUtil();
ftputil.downloadFile(filename, localPath);
}
//get set方法自己添加
//..............
}
具體使用
第一步:配置spring加載properties文件
applicationContext.xml
<context:property-placeholder location="classpath:*.properties"/> ftp.properties ftp.host=192.168.100.77 ftp.port=21 ftp.username=ftpuser ftp.password=ftp54321 ftp.basePath=/home/ftpuser/
第二步:將工具類聲明為bean
xml方式
<bean id="ftpUtil" class="com.cky.util.FtpUtil">
<property name="host" value="${ftp.host}"></property>
<property name="port" value="${ftp.port}"></property>
<property name="username" value="${ftp.username}"></property>
<property name="password" value="${ftp.password}"></property>
<property name="basePath" value="${ftp.basePath}"></property>
</bean>
注解方式,組件掃描
<context:component-scan base-package="com.cky.util"></context:component-scan>
第三部:注入使用
@Autowired private FtpUtil ftpUtil;
總結(jié)
以上所述是小編給大家介紹的Spring FTP上傳下載工具類遇到問(wèn)題小結(jié),希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
MyBatis中關(guān)于resultType和resultMap的區(qū)別介紹
MyBatis中在查詢進(jìn)行select映射的時(shí)候,返回類型可以用resultType,也可以用resultMap,那么MyBatis中關(guān)于resultType和resultMap的區(qū)別是什么呢?下面小編通過(guò)本文給大家解答下2016-09-09
淺談@RequestBody和@RequestParam可以同時(shí)使用
這篇文章主要介紹了@RequestBody和@RequestParam可以同時(shí)使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
Java 向上轉(zhuǎn)型和向下轉(zhuǎn)型的詳解
這篇文章主要介紹了 Java 向上轉(zhuǎn)型和向下轉(zhuǎn)型的詳解的相關(guān)資料,需要的朋友可以參考下2017-04-04
?基于Java解決華為機(jī)試之字符串合并處理實(shí)操
這篇文章主要介紹了基于Java解決華為機(jī)試之字符串合并處理,文章以實(shí)操展開(kāi)主題內(nèi)容,具有一的參考價(jià)值,需要的小伙伴可以參考一下,希望對(duì)工作中的你有所幫助2022-02-02
JAVA?GUI基礎(chǔ)與MouseListener用法
這篇文章主要介紹了JAVA?GUI基礎(chǔ)與MouseListener用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12

