java編寫ftp
mina.apache.org 伺服器端,客戶端都有!開源的!
『貳』 怎麼用Java實現FTP上傳
sun.net.ftp.FtpClient.,該類庫主要提供了用於建立FTP連接的類。利用這些類的方法,編程人員可以遠程登錄到FTP伺服器,列舉該伺服器上的目錄,設置傳輸協議,以及傳送文件。FtpClient類涵蓋了幾乎所有FTP的功能,FtpClient的實例變數保存了有關建立"代理"的各種信息。下面給出了這些實例變數:
public static boolean useFtpProxy
這個變數用於表明FTP傳輸過程中是否使用了一個代理,因此,它實際上是一個標記,此標記若為TRUE,表明使用了一個代理主機。
public static String ftpProxyHost
此變數只有在變數useFtpProxy為TRUE時才有效,用於保存代理主機名。
public static int ftpProxyPort此變數只有在變數useFtpProxy為TRUE時才有效,用於保存代理主機的埠地址。
FtpClient有三種不同形式的構造函數,如下所示:
1、public FtpClient(String hostname,int port)
此構造函數利用給出的主機名和埠號建立一條FTP連接。
2、public FtpClient(String hostname)
此構造函數利用給出的主機名建立一條FTP連接,使用默認埠號。
3、FtpClient()
此構造函數將創建一FtpClient類,但不建立FTP連接。這時,FTP連接可以用openServer方法建立。
一旦建立了類FtpClient,就可以用這個類的方法來打開與FTP伺服器的連接。類ftpClient提供了如下兩個可用於打開與FTP伺服器之間的連接的方法。
public void openServer(String hostname)
這個方法用於建立一條與指定主機上的FTP伺服器的連接,使用默認埠號。
public void openServer(String host,int port)
這個方法用於建立一條與指定主機、指定埠上的FTP伺服器的連接。
打開連接之後,接下來的工作是注冊到FTP伺服器。這時需要利用下面的方法。
public void login(String username,String password)
此方法利用參數username和password登錄到FTP伺服器。使用過Intemet的用戶應該知道,匿名FTP伺服器的登錄用戶名為anonymous,密碼一般用自己的電子郵件地址。
下面是FtpClient類所提供的一些控制命令。
public void cd(String remoteDirectory):該命令用於把遠程系統上的目錄切換到參數remoteDirectory所指定的目錄。
public void cdUp():該命令用於把遠程系統上的目錄切換到上一級目錄。
public String pwd():該命令可顯示遠程系統上的目錄狀態。
public void binary():該命令可把傳輸格式設置為二進制格式。
public void ascii():該命令可把傳輸協議設置為ASCII碼格式。
public void rename(String string,String string1):該命令可對遠程系統上的目錄或者文件進行重命名操作。
除了上述方法外,類FtpClient還提供了可用於傳遞並檢索目錄清單和文件的若干方法。這些方法返回的是可供讀或寫的輸入、輸出流。下面是其中一些主要的方法。
public TelnetInputStream list()
返回與遠程機器上當前目錄相對應的輸入流。
public TelnetInputStream get(String filename)
獲取遠程機器上的文件filename,藉助TelnetInputStream把該文件傳送到本地。
public TelnetOutputStream put(String filename)
以寫方式打開一輸出流,通過這一輸出流把文件filename傳送到遠程計算機
package myUtil;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
/**
 * ftp上傳,下載
 * 
 * @author why 2009-07-30
 * 
 */
public class FtpUtil {
private String ip = "";
private String username = "";
private String password = "";
private int port = -1;
private String path = "";
FtpClient ftpClient = null;
OutputStream os = null;
FileInputStream is = null;
public FtpUtil(String serverIP, String username, String password) {
this.ip = serverIP;
this.username = username;
this.password = password;
}
public FtpUtil(String serverIP, int port, String username, String password) {
this.ip = serverIP;
this.username = username;
this.password = password;
this.port = port;
}
/**
* 連接ftp伺服器
* 
* @throws IOException
*/
public boolean connectServer() {
ftpClient = new FtpClient();
try {
if (this.port != -1) {
ftpClient.openServer(this.ip, this.port);
} else {
ftpClient.openServer(this.ip);
}
ftpClient.login(this.username, this.password);
if (this.path.length() != 0) {
ftpClient.cd(this.path);// path是ftp服務下主目錄的子目錄
}
ftpClient.binary();// 用2進制上傳、下載
System.out.println("已登錄到\"" + ftpClient.pwd() + "\"目錄");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 斷開與ftp伺服器連接
* 
* @throws IOException
*/
public boolean closeServer() {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (ftpClient != null) {
ftpClient.closeServer();
}
System.out.println("已從伺服器斷開");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 檢查文件夾在當前目錄下是否存在
* 
* @param dir
*@return
*/
private boolean isDirExist(String dir) {
String pwd = "";
try {
pwd = ftpClient.pwd();
ftpClient.cd(dir);
ftpClient.cd(pwd);
} catch (Exception e) {
return false;
}
return true;
}
/**
* 在當前目錄下創建文件夾
* 
* @param dir
* @return
* @throws Exception
*/
private boolean createDir(String dir) {
try {
ftpClient.ascii();
StringTokenizer s = new StringTokenizer(dir, "/"); // sign
s.countTokens();
String pathName = ftpClient.pwd();
while (s.hasMoreElements()) {
pathName = pathName + "/" + (String) s.nextElement();
try {
ftpClient.sendServer("MKD " + pathName + "\r\n");
} catch (Exception e) {
e = null;
return false;
}
ftpClient.readServerResponse();
}
ftpClient.binary();
return true;
} catch (IOException e1) {
e1.printStackTrace();
return false;
}
}
/**
* ftp上傳 如果伺服器段已存在名為filename的文件夾,該文件夾中與要上傳的文件夾中同名的文件將被替換
* 
* @param filename
*            要上傳的文件(或文件夾)名
* @return
* @throws Exception
*/
public boolean upload(String filename) {
String newname = "";
if (filename.indexOf("/") > -1) {
newname = filename.substring(filename.lastIndexOf("/") + 1);
} else {
newname = filename;
}
return upload(filename, newname);
}
/**
* ftp上傳 如果伺服器段已存在名為newName的文件夾,該文件夾中與要上傳的文件夾中同名的文件將被替換
* 
* @param fileName
*            要上傳的文件(或文件夾)名
* @param newName
*            伺服器段要生成的文件(或文件夾)名
* @return
*/
public boolean upload(String fileName, String newName) {
try {
String savefilename = new String(fileName.getBytes("GBK"),
"GBK");
File file_in = new File(savefilename);// 打開本地待長傳的文件
if (!file_in.exists()) {
throw new Exception("此文件或文件夾[" + file_in.getName() + "]有誤或不存在!");
}
if (file_in.isDirectory()) {
upload(file_in.getPath(), newName, ftpClient.pwd());
} else {
uploadFile(file_in.getPath(), newName);
}
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
return true;
} catch (Exception e) {
e.printStackTrace();
System.err.println("Exception e in Ftp upload(): " + e.toString());
return false;
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 真正用於上傳的方法
* 
* @param fileName
* @param newName
* @param path
* @throws Exception
*/
private void upload(String fileName, String newName, String path)
throws Exception {
String savefilename = new String(fileName.getBytes("ISO-8859-1"), "GBK");
File file_in = new File(savefilename);// 打開本地待長傳的文件
if (!file_in.exists()) {
throw new Exception("此文件或文件夾[" + file_in.getName() + "]有誤或不存在!");
}
if (file_in.isDirectory()) {
if (!isDirExist(newName)) {
createDir(newName);
}
ftpClient.cd(newName);
File sourceFile[] = file_in.listFiles();
for (int i = 0; i < sourceFile.length; i++) {
if (!sourceFile[i].exists()) {
continue;
}
if (sourceFile[i].isDirectory()) {
this.upload(sourceFile[i].getPath(), sourceFile[i]
.getName(), path + "/" + newName);
} else {
this.uploadFile(sourceFile[i].getPath(), sourceFile[i]
.getName());
}
}
} else {
uploadFile(file_in.getPath(), newName);
}
ftpClient.cd(path);
}
/**
* upload 上傳文件
* 
* @param filename
*            要上傳的文件名
* @param newname
*            上傳後的新文件名
* @return -1 文件不存在 >=0 成功上傳,返迴文件的大小
* @throws Exception
*/
public long uploadFile(String filename, String newname) throws Exception {
long result = 0;
TelnetOutputStream os = null;
FileInputStream is = null;
try {
java.io.File file_in = new java.io.File(filename);
if (!file_in.exists())
return -1;
os = ftpClient.put(newname);
result = file_in.length();
is = new FileInputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
} finally {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
}
return result;
}
/**
* 從ftp下載文件到本地
* 
* @param filename
*            伺服器上的文件名
* @param newfilename
*            本地生成的文件名
* @return
* @throws Exception
*/
public long downloadFile(String filename, String newfilename) {
long result = 0;
TelnetInputStream is = null;
FileOutputStream os = null;
try {
is = ftpClient.get(filename);
java.io.File outfile = new java.io.File(newfilename);
os = new FileOutputStream(outfile);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
result = result + c;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 取得相對於當前連接目錄的某個目錄下所有文件列表
* 
* @param path
* @return
*/
public List getFileList(String path) {
List list = new ArrayList();
DataInputStream dis;
try {
dis = new DataInputStream(ftpClient.nameList(this.path + path));
String filename = "";
while ((filename = dis.readLine()) != null) {
list.add(filename);
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
public static void main(String[] args) {
FtpUtil ftp = new FtpUtil("192.168.11.11", "111", "1111");
ftp.connectServer();
boolean result = ftp.upload("C:/Documents and Settings/ipanel/桌面/java/Hibernate_HQL.docx", "amuse/audioTest/music/Hibernate_HQL.docx");
System.out.println(result ? "上傳成功!" : "上傳失敗!");
ftp.closeServer();
/**
* FTP遠程命令列表 USER PORT RETR ALLO DELE SITE XMKD CDUP FEAT PASS PASV STOR
* REST CWD STAT RMD XCUP OPTS ACCT TYPE APPE RNFR XCWD HELP XRMD STOU
* AUTH REIN STRU SMNT RNTO LIST NOOP PWD SIZE PBSZ QUIT MODE SYST ABOR
* NLST MKD XPWD MDTM PROT
* 在伺服器上執行命令,如果用sendServer來執行遠程命令(不能執行本地FTP命令)的話,所有FTP命令都要加上\r\n
* ftpclient.sendServer("XMKD /test/bb\r\n"); //執行伺服器上的FTP命令
* ftpclient.readServerResponse一定要在sendServer後調用
* nameList("/test")獲取指目錄下的文件列表 XMKD建立目錄,當目錄存在的情況下再次創建目錄時報錯 XRMD刪除目錄
* DELE刪除文件
*/
}
}
『叄』 java 實現ftp上傳如何創建文件夾
這個功能我也剛寫完,不過我也是得益於同行,現在我也把自己的分享給大家,希望能對大家有所幫助,因為自己的項目不涉及到創建文件夾,也僅作分享,不喜勿噴謝謝!
interface:
packagecom.sunline.bank.ftputil;
importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importorg.apache.commons.net.ftp.FTPClient;
publicinterfaceIFtpUtils{
/**
*ftp登錄
*@paramhostname主機名
*@paramport埠號
*@paramusername用戶名
*@parampassword密碼
*@return
*/
publicFTPClientloginFtp(Stringhostname,Integerport,Stringusername,Stringpassword);
/**
*上穿文件
*@paramhostname主機名
*@paramport埠號
*@paramusername用戶名
*@parampassword密碼
*@paramfpathftp路徑
*@paramlocalpath本地路徑
*@paramfileName文件名
*@return
*/
(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName);
/**
*批量下載文件
*@paramhostname
*@paramport
*@paramusername
*@parampassword
*@paramfpath
*@paramlocalpath
*@paramfileName源文件名
*@paramfilenames需要修改成的文件名
*@return
*/
publicbooleandownloadFileList(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName,Stringfilenames);
/**
*修改文件名
*@paramlocalpath
*@paramfileName源文件名
*@paramfilenames需要修改的文件名
*/
(Stringlocalpath,StringfileName,Stringfilenames);
/**
*關閉流連接、ftp連接
*@paramftpClient
*@parambufferRead
*@parambuffer
*/
publicvoidcloseFtpConnection(FTPClientftpClient,,BufferedInputStreambuffer);
}
impl:
packagecom.sunline.bank.ftputil;
importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importorg.apache.commons.net.ftp.FTPClient;
importorg.apache.commons.net.ftp.FTPFile;
importorg.apache.commons.net.ftp.FTPReply;
importcommon.Logger;
{
privatestaticLoggerlog=Logger.getLogger(FtpUtilsImpl.class);
FTPClientftpClient=null;
Integerreply=null;
@Override
publicFTPClientloginFtp(Stringhostname,Integerport,Stringusername,Stringpassword){
ftpClient=newFTPClient();
try{
ftpClient.connect(hostname,port);
ftpClient.login(username,password);
ftpClient.setControlEncoding("utf-8");
reply=ftpClient.getReplyCode();
ftpClient.setDataTimeout(60000);
ftpClient.setConnectTimeout(60000);
//設置文件類型為二進制(避免解壓縮文件失敗)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//開通數據埠傳輸數據,避免阻塞
ftpClient.enterLocalActiveMode();
if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
log.error("連接FTP失敗,用戶名或密碼錯誤");
}else{
log.info("FTP連接成功");
}
}catch(Exceptione){
if(!FTPReply.isPositiveCompletion(reply)){
try{
ftpClient.disconnect();
}catch(IOExceptione1){
log.error("登錄FTP失敗,請檢查FTP相關配置信息是否正確",e1);
}
}
}
returnftpClient;
}
@Override
@SuppressWarnings("resource")
(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName){
booleanflag=false;
ftpClient=loginFtp(hostname,port,username,password);
BufferedInputStreambuffer=null;
try{
buffer=newBufferedInputStream(newFileInputStream(localpath+fileName));
ftpClient.changeWorkingDirectory(fpath);
fileName=newString(fileName.getBytes("utf-8"),ftpClient.DEFAULT_CONTROL_ENCODING);
if(!ftpClient.storeFile(fileName,buffer)){
log.error("上傳失敗");
returnflag;
}
buffer.close();
ftpClient.logout();
flag=true;
returnflag;
}catch(Exceptione){
e.printStackTrace();
}finally{
closeFtpConnection(ftpClient,null,buffer);
log.info("文件上傳成功");
}
returnfalse;
}
@Override
publicbooleandownloadFileList(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName,Stringfilenames){
ftpClient=loginFtp(hostname,port,username,password);
booleanflag=false;
=null;
if(fpath.startsWith("/")&&fpath.endsWith("/")){
try{
//切換到當前目錄
this.ftpClient.changeWorkingDirectory(fpath);
this.ftpClient.enterLocalActiveMode();
FTPFile[]ftpFiles=this.ftpClient.listFiles();
for(FTPFilefiles:ftpFiles){
if(files.isFile()){
System.out.println("=================="+files.getName());
FilelocalFile=newFile(localpath+"/"+files.getName());
bufferRead=newBufferedOutputStream(newFileOutputStream(localFile));
ftpClient.retrieveFile(files.getName(),bufferRead);
bufferRead.flush();
}
}
ftpClient.logout();
flag=true;
}catch(IOExceptione){
e.printStackTrace();
}finally{
closeFtpConnection(ftpClient,bufferRead,null);
log.info("文件下載成功");
}
}
modifiedLocalFileName(localpath,fileName,filenames);
returnflag;
}
@Override
(Stringlocalpath,StringfileName,Stringfilenames){
Filefile=newFile(localpath);
File[]fileList=file.listFiles();
if(file.exists()){
if(null==fileList||fileList.length==0){
log.error("文件夾是空的");
}else{
for(Filedata:fileList){
Stringorprefix=data.getName().substring(0,data.getName().lastIndexOf("."));
Stringprefix=fileName.substring(0,fileName.lastIndexOf("."));
System.out.println("index==="+orprefix+"prefix==="+prefix);
if(orprefix.contains(prefix)){
booleanf=data.renameTo(newFile(localpath+"/"+filenames));
System.out.println("f============="+f);
}else{
log.error("需要重命名的文件不存在,請檢查。。。");
}
}
}
}
}
@Override
publicvoidcloseFtpConnection(FTPClientftpClient,,BufferedInputStreambuffer){
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=bufferRead){
try{
bufferRead.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=buffer){
try{
buffer.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
publicstaticvoidmain(String[]args)throwsIOException{
Stringhostname="xx.xxx.x.xxx";
Integerport=21;
Stringusername="edwftp";
Stringpassword="edwftp";
Stringfpath="/etl/etldata/back/";
StringlocalPath="C:/Users/Administrator/Desktop/ftp下載/";
StringfileName="test.txt";
Stringfilenames="ok.txt";
FtpUtilsImplftp=newFtpUtilsImpl();
/*ftp.modifiedLocalFileName(localPath,fileName,filenames);*/
ftp.downloadFileList(hostname,port,username,password,fpath,localPath,fileName,filenames);
/*ftp.uploadLocalFilesToFtp(hostname,port,username,password,fpath,localPath,fileName);*/
/*ftp.modifiedLocalFileName(localPath);*/
}
}
『肆』 怎麼用Java開發FTP客戶端
摘要
本文解釋了如何利用庫用Java語言編寫FTP客戶端代碼。它比較了FTP庫的一個完全列表,演示了每個庫的優點和缺點,並且幫助決策者為他們的需要選擇適當的庫。另外,本文闡述了Fa?ade模式如何在取代一個庫時改變管理。最後,作者Jean-Pierre Norguet討論並解決了由於缺乏權威性的說明書引起的一些問題。
讓我們假設一個情景:我們要編寫一個純Java應用程序,該程序必須從運行FTP伺服器的遠程計算機上下載文件。我們也通過遠程文件信息,像名字、日期、或者尺寸,來過濾下載。
自己來寫一個FTP協議處理,盡管是有可能,並且可能很有趣。但是這樣做也有可能有困難、花費長時間、並且有潛在的風險。既然我們不肯花費時間、精力、或者金錢自己來寫一個處理器,那我們推薦使用一個可重用的現有的軟體組件。萬維網上有並且大量的庫可供使用。有了一個FTP客戶端庫,下載一個文件用Java語言編寫就像下面一樣簡單:
FTPClient ftpClient = new FTPClient();
ftpClient.connect("ftp.foo.com", "user01", "pass1234");
ftpClient.download("C:\\Temp\\", "README.txt");
// Eventually other operations here ...
ftpClient.disconnect();
尋找一個適合我們需要的高質量的Java FTP客戶端庫並不像他看起來那麼簡單;它可能相當困難。要找到一個Java FTP客戶端庫需要花一些時間。接著,在我們找到所有的已存在的庫之後,我們選哪個?每個庫適合不同的需要。庫在質量上是不等的,並且它們的設計有本質的區別。每個提供一套不同的屬性和使用不同類型的行話來描述他們。
因此,計算和比較FTP客戶端庫證明是困難而且令人迷惑的。重復使用已存在的組件是一個值得推薦的過程,但在這個例子中,啟動它也是令人沮喪的。並且這有點羞愧:在選好的一個好的FTP庫之後,剩下的工作就是常式了。
本文旨在使選擇過程簡短、容易、並且有價值。我首先列出了所有的FTP客戶端庫。接著,我定義和描述了庫應該用某種方式找到的相關標準的一個表格。最後,我列出了一個總瀏覽的矩陣,該矩陣給出了庫間相互比較的過程的快速瀏覽。所有的信息提供了我們作出一個迅速、可靠、和長期的決定所需的每件事。
使用JDK(Java 開發工具集)的FTP支持
用於FTP的訪問規范是用於注釋的請求:959(RFC959)。Sun Microsystems提供了JDK的一個RFC959執行。但是它是內部的、非文檔化的、並且不提供任何資源。當RFC959在尚未公開時,它實際上是執行RFC1738、URL規范的一個公共界面的後終端。如圖1。
圖1. 使用JDK的FTP支持。
     RFC1738的一個執行過程在JDK中作為標准給出。它為基本的FTP傳送做一個可推理的工作。它是公共的、文檔化的、並且提供源代碼。要使用它,我們可編寫下面語句:
URL url = new URL("ftp://user01:[email protected]/README.txt;type=i");
URLConnection urlc = url.openConnection();
InputStream is = urlc.getInputStream(); // To download
OutputStream os = urlc.getOutputStream(); // To upload
   使用JDK的FTP客戶端嚴格的遵守標准推薦,但它有以下幾個說明:
     它從根本上區別於第三方的FTP客戶端庫;這些執行RFC959而不是RFC1738
     RFC959用大多數的桌面FTP客戶端工具執行。許多Java程序員使用這些工具連接到FTP伺服器上。作為一個嘗試,這些工具及有可能優先於類似的RFC959庫。
     URL 和URLConnection類只開放用於通訊的流。Sun庫不為構造原始的FTP伺服器響應成為像String、 File、 RemoteFile、 或者 Calendar之類的更合用的Java對象而提供直接支持。所以我們不得不編寫更多的代碼,只是為了把數據寫入一個文件中或者開始一個目錄列表。
     正像RFC1738的3.2部分解釋的一樣,"最優化",FTP URL在每個操作後要求關閉(控制)連接。這對於傳送許多小文件是一種浪費、並且毫無效率。而且,作了特別限制FTP伺服器可能把會這樣一個通訊開銷認為一個是惡毒的網路攻擊或者濫用而拒絕提供進一步的服務。
     最後,它缺乏幾個有用的屬性。
由於以上所有或者某種原因,可優先使用一個第三方的庫。下面部分列出了可供選擇的第三方的庫。
見:http://www.javaworld.com/javaworld/jw-04-2003/ftp/jw-0404-ftptable.html
『伍』 用java有一個ftp路徑地址,需要把傳送一些數據到ftp中怎樣實現
1.使用的FileZillaServer開源,安裝過後建立的本地FTP伺服器。2.使用的apache上FTP工具包,引用到工程目錄中。3.IDE,Eclipse,JDK6上傳和目錄的實現原理:對每一個層級的目錄進行判斷,是為目錄類型、還是文件類型。如果為目錄類型,採用遞歸調用方法,檢查到最底層的目錄為止結束。如果為文件類型,則調用上傳或者方法對文件進行上傳或者操作。貼出代碼:(其中有些沒有代碼,可以看看,還是很有用處的)!
『陸』 怎樣用java開發ftp客戶端
package zn.ccfccb.util;
import hkrt.b2b.view.util.Log;
import hkrt.b2b.view.util.ViewUtil;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import zn.ccfccb.util.CCFCCBUtil;
import zn.ccfccb.util.ZipUtilAll;
public class CCFCCBFTP {
    /**
     * 上傳文件
     *
     * @param fileName
     * @param plainFilePath 明文文件路徑路徑
     * @param filepath
     * @return 
     * @throws Exception
     */
    public static String fileUploadByFtp(String plainFilePath, String fileName, String filepath) throws Exception {
        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;
        FTPClient ftpClient = new FTPClient();
        String bl = "false";
        try {
            fis = new FileInputStream(plainFilePath);
            bos = new ByteArrayOutputStream(fis.available());
            byte[] buffer = new byte[1024];
            int count = 0;
            while ((count = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, count);
            }
            bos.flush();
            Log.info("加密上傳文件開始");
            Log.info("連接遠程上傳伺服器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);
            ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
            ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
//            Log.info("連接遠程上傳伺服器"+"192.168.54.106:"+2021);
//            ftpClient.connect("192.168.54.106", 2021);
//            ftpClient.login("hkrt-CCFCCBHK", "3OLJheziiKnkVcu7Sigz");
            FTPFile[] fs;
            fs = ftpClient.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(filepath)) {
                    bl="true";
                    ftpClient.changeWorkingDirectory("/"+filepath+"");
                }
            }
             Log.info("檢查文件路徑是否存在:/"+filepath);
             if("false".equals(bl)){
                 ViewUtil.dataSEErrorPerformedCommon( "查詢文件路徑不存在:"+"/"+filepath);
                  return bl;
            }
            ftpClient.setBufferSize(1024);
            ftpClient.setControlEncoding("GBK");
            // 設置文件類型(二進制)
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.storeFile(fileName, fis);
            Log.info("上傳文件成功:"+fileName+"。文件保存路徑:"+"/"+filepath+"/");
            return bl;
        } catch (Exception e) {
            throw e;
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e) {
                    Log.info(e.getLocalizedMessage(), e);
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (Exception e) {
                    Log.info(e.getLocalizedMessage(), e);
                }
            }
        }
    
    }
    /**
     *下載並解壓文件
     *
     * @param localFilePath
     * @param fileName
     * @param routeFilepath
     * @return 
     * @throws Exception
     */
    public static String fileDownloadByFtp(String localFilePath, String fileName,String routeFilepath) throws Exception {
        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;
        FileOutputStream fos = null;
        FTPClient ftpClient = new FTPClient();
        String SFP = System.getProperty("file.separator");
        String bl = "false";
        try {
            Log.info("下載並解密文件開始");
            Log.info("連接遠程下載伺服器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);
            ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
            ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
//            ftpClient.connect(CMBCUtil.CMBCHOSTNAME, 2021);
//            ftpClient.login(CMBCUtil.CMBCLOGINNAME, CMBCUtil.CMBCLOGINPASSWORD);
            FTPFile[] fs;        
            
            ftpClient.makeDirectory(routeFilepath);
            ftpClient.changeWorkingDirectory(routeFilepath);
            bl = "false";
            fs = ftpClient.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                        bl = "true";
                        Log.info("下載文件開始。");
                        ftpClient.setBufferSize(1024);
                        // 設置文件類型(二進制)
                        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                        InputStream is = ftpClient.retrieveFileStream(fileName);
                        bos = new ByteArrayOutputStream(is.available());
                        byte[] buffer = new byte[1024];
                        int count = 0;
                        while ((count = is.read(buffer)) != -1) {
                            bos.write(buffer, 0, count);
                        }
                        bos.flush();
                        fos = new FileOutputStream(localFilePath+SFP+fileName);
                        fos.write(bos.toByteArray());
                        Log.info("下載文件結束:"+localFilePath);
                }
            }
            Log.info("檢查文件是否存:"+fileName+"  "+bl);
            if("false".equals(bl)){
                 ViewUtil.dataSEErrorPerformedCommon("查詢無結果,請稍後再查詢。");
                 return bl;
            }
          return bl;
        } catch (Exception e) {
            throw e;
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e) {
                    Log.info(e.getLocalizedMessage(), e);
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (Exception e) {
                    Log.info(e.getLocalizedMessage(), e);
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                    Log.info(e.getLocalizedMessage(), e);
                }
            }
        }
    }
//       調用樣例:
    public static void main(String[] args) {
        try {
			// 密鑰/res/20150228
//         ZipUtilAll.unZip(new File(("D:/123/123.zip")), "D:/123/");
//         ZipDemo1232.unZip(new File(("D:/123/123.zip")), "D:/123/");
            // 明文文件路徑
            String plainFilePath = "D:/req_20150204_0011.txt";
            // 密文文件路徑
            String secretFilePath = "req_20150204_00134.txt";
			// 加密
//			encodeAESFile(key, plainFilePath, secretFilePath);
          fileDownloadByFtp("D://123.zip","123.zip","req/20150228");
          ZipUtilAll.unZip("D://123.zip", "D:/123/李筱/");
            // 解密
            plainFilePath = "D:/123.sql";
//			secretFilePath = "D:/test11111.sql";
//			decodeAESFile(key, plainFilePath, secretFilePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
『柒』 JAVA 如何實現FTP遠程路徑
package nc.ui.doc.doc_007;  
 
import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 
import nc.itf.doc.DocDelegator;  
 import nc.vo.doc.doc_007.DirVO;  
 import nc.vo.pub.BusinessException;  
 import nc.vo.pub.SuperVO;  
 
import org.apache.commons.net.ftp.FTPClient;  
 import org.apache.commons.net.ftp.FTPFile;  
 import org.apache.commons.net.ftp.FTPReply;  
 import org.apache.commons.net.ftp.FTP;  
public class FtpTool {  
private FTPClient ftp;  
 
private String romateDir = "";  
 
private String userName = "";  
 
private String password = "";  
 
private String host = "";  
 
private String port = "21";  
 
public FtpTool(String url) throws IOException {  
 //String url="ftp://user:password@ip:port/ftptest/psd";  
 int len = url.indexOf("//");  
 String strTemp = url.substring(len + 2);  
 len = strTemp.indexOf(":");  
 userName = strTemp.substring(0, len);  
 strTemp = strTemp.substring(len + 1);  
 
len = strTemp.indexOf("@");  
 password = strTemp.substring(0, len);  
 strTemp = strTemp.substring(len + 1);  
 host = "";  
 len = strTemp.indexOf(":");  
 if (len < 0)//沒有設置埠  
 {  
 port = "21";  
 len = strTemp.indexOf("/");  
 if (len > -1) {  
 host = strTemp.substring(0, len);  
 strTemp = strTemp.substring(len + 1);  
 } else {  
 strTemp = "";  
 }  
 } else {  
 host = strTemp.substring(0, len);  
 strTemp = strTemp.substring(len + 1);  
 len = strTemp.indexOf("/");  
 if (len > -1) {  
 port = strTemp.substring(0, len);  
 strTemp = strTemp.substring(len + 1);  
 } else {  
 port = "21";  
 strTemp = "";  
 }  
 }  
 romateDir = strTemp;  
 ftp = new FTPClient();  
 ftp.connect(host, FormatStringToInt(port));  
 
}  
 
public FtpTool(String host, int port) throws IOException {  
 ftp = new FTPClient();  
 ftp.connect(host, port);  
 }  
 
public String login(String username, String password) throws IOException {  
 this.ftp.login(username, password);  
 return this.ftp.getReplyString();  
 }  
 
public String login() throws IOException {  
 this.ftp.login(userName, password);  
 System.out.println("ftp用戶: " + userName);  
 System.out.println("ftp密碼: " + password);  
 if (!romateDir.equals(""))  
 System.out.println("cd " + romateDir);  
 ftp.changeWorkingDirectory(romateDir);  
 return this.ftp.getReplyString();  
 }  
 
public boolean upload(String pathname, String filename) throws IOException, BusinessException {  
 
int reply;  
 int j;  
 String m_sfilename = null;  
 filename = CheckNullString(filename);  
 if (filename.equals(""))  
 return false;  
 reply = ftp.getReplyCode();  
 if (!FTPReply.isPositiveCompletion(reply)) {  
 ftp.disconnect();  
 System.out.println("FTP server refused connection.");  
 System.exit(1);  
 }  
 FileInputStream is = null;  
 try {  
 File file_in;  
 if (pathname.endsWith(File.separator)) {  
 file_in = new File(pathname + filename);  
 } else {  
 file_in = new File(pathname + File.separator + filename);  
 }  
 if (file_in.length() == 0) {  
 System.out.println("上傳文件為空!");  
 return false;  
 }   
   //產生隨機數最大到99   
   j = (int)(Math.random()*100);  
   m_sfilename = String.valueOf(j) + ".pdf"; // 生成的文件名  
 is = new FileInputStream(file_in);  
 ftp.setFileType(FTP.BINARY_FILE_TYPE);  
 ftp.storeFile(m_sfilename, is);  
 ftp.logout();  
} finally {  
 if (is != null) {  
 is.close();  
 }  
 }  
 System.out.println("上傳文件成功!");  
 return true;  
 }  
public boolean delete(String filename) throws IOException {  
 
FileInputStream is = null;  
 boolean retValue = false;  
 try {  
 retValue = ftp.deleteFile(filename);  
 ftp.logout();  
 } finally {  
 if (is != null) {  
 is.close();  
 }  
 }  
 return retValue;  
 
}  
 
public void close() {  
 if (ftp.isConnected()) {  
 try {  
 ftp.disconnect();  
 } catch (IOException e) {  
 e.printStackTrace();  
 }  
 }  
 }  
 
public static int FormatStringToInt(String p_String) {  
 int intRe = 0;  
 if (p_String != null) {  
 if (!p_String.trim().equals("")) {  
 try {  
 intRe = Integer.parseInt(p_String);  
 } catch (Exception ex) {  
 
}  
 }  
 }  
 return intRe;  
 }  
 
public static String CheckNullString(String p_String) {  
 if (p_String == null)  
 return "";  
 else  
 return p_String;  
 }  
 
public boolean downfile(String pathname, String filename) {  
 
String outputFileName = null;  
 boolean retValue = false;  
 try {  
 FTPFile files[] = ftp.listFiles();  
 int reply = ftp.getReplyCode();  
 
////////////////////////////////////////////////  
 if (!FTPReply.isPositiveCompletion(reply)) {  
 try {  
 throw new Exception("Unable to get list of files to dowload.");  
 } catch (Exception e) {  
 // TODO Auto-generated catch block  
 e.printStackTrace();  
 }  
 }  
 
/////////////////////////////////////////////////////  
 if (files.length == 0) {  
 System.out.println("No files are available for download.");  
 }else {  
 for (int i=0; i <files.length; i++) {  
 System.out.println("Downloading file "+files[i].getName()+"Size:"+files[i].getSize());  
 outputFileName = pathname + filename + ".pdf";  
 //return outputFileName;  
 File f = new File(outputFileName);  
 
//////////////////////////////////////////////////////  
 retValue = ftp.retrieveFile(outputFileName, new FileOutputStream(f));  
 
if (!retValue) {  
 try {  
 throw new Exception ("Downloading of remote file"+files[i].getName()+" failed. ftp.retrieveFile() returned false.");  
 } catch (Exception e) {  
 // TODO Auto-generated catch block  
 e.printStackTrace();  
 }  
 }  
 
}  
 }  
 
/////////////////////////////////////////////////////////////  
 } catch (IOException e) {  
 // TODO Auto-generated catch block  
 e.printStackTrace();  
 }  
 return retValue;  
 }  
 
}
