當前位置:首頁 » 文件傳輸 » java遠程密鑰創建ftp
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

java遠程密鑰創建ftp

發布時間: 2023-05-29 09:10:00

⑴ 怎樣用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用戶和密碼

這個取決於你的ftp伺服器,IIS,Mozila...規則不一樣

⑶ 使用Java實現FTP伺服器

FTP是Internet 上用來傳送文件的協議 在Internet上通過FTP 伺服器可以進行文件的上傳(Upload)或下載(Download) FTP是實時聯機服務 在使用它之前必須是具有該服務早汪的一個用戶(用戶名和口令) 工作時客戶端必須先登錄到作為伺服器一方的計算機上 用戶登錄後可以進行文件搜索和文件傳送等有關操作 如改變當前工作目錄 列文件目錄 設置傳輸參數及傳送文件等 使用FTP可以傳送所有類型的文件 如文本文件 二進制可執行文件 圖象文件 聲音文件和數據壓縮文件等 FTP 命令 FTP 的主要操作都是基於各種命令基礎之上的 常用的命令有 ◆ 設置傳輸模式 它包括ASCⅡ(文本) 和BINARY 二進制模式 ◆ 目錄操作 改變或顯示遠程計算機的當前目錄(cd dir/ls 命令) ◆ 連接操作 open命令用於建立同遠程計算機的連接 close命令用於關閉連接 禪睜隱 ◆ 發送操作 put命令用於傳送文件到遠程計算機 mput 命令用於傳送多個文件到遠程計算機 ◆ 獲取操作 get命令用於接收一個文件 mget命令用於接收多個文件 編程思路 根據FTP的工作原理 在主函數中建立一個伺服器套接字埠 等待客戶端請求 一旦客戶端請求被接受 伺服器程序就建立一個伺服器分線程 處理客戶端的命令 如果客戶賀廳端需要和伺服器端進行文件的傳輸 則建立一個新的套接字連接來完成文件的操作

編程技巧說明 主函數設計 在主函數中 完成伺服器埠的偵聽和服務線程的創建 我們利用一個靜態字元串變數initDir 來保存伺服器線程運行時所在的工作目錄 伺服器的初始工作目錄是由程序運行時用戶輸入的 預設為C盤的根目錄 具體的代碼如下 public class ftpServer extends Thread{ private Socket socketClient; private int counter; private static String initDir; public static void main(String[] args){ if(args length != ) { initDir = args[ ]; }else{ initDir = c: ;} int i = ; try{ System out println( ftp server started! ) //監聽 號埠 ServerSocket s = new ServerSocket( ) for( ){ //接受客戶端請求 Socket ining = s accept() //創建服務線程 new ftpServer(ining i) start() i++; } }catch(Exception e){} } 線程類的設計 線程類的主要設計都是在run()方法中實現 用run()方法得到客戶端的套接字信息 根據套接字得到輸入流和輸出流 向客戶端發送歡迎信息 FTP命令的處理 ( ) 訪問控制命令 ◆ user name(user) 和 password (pass) 命令處理代碼如下 if(str startsWith( USER )){ user = str substring( ) user = user trim() out println( Password ) } if(str startsWith( PASS )) out println( User +user+ logged in ) User 命令和 Password 命令分別用來提交客戶端用戶輸入的用戶名和口令 ◆ CWD (CHANGE WORKING DIRECTORY) 命令處理代碼如下 if(str startsWith( CWD )){ String str = str substring( ) dir = dir+ / +str trim() out println( CWD mand succesful ) } 該命令改變工作目錄到用戶指定的目錄 ◆ CDUP (CHANGE TO PARENT DIRECTORY) 命令處理代碼如下 if(str startsWith( CDUP )){ int n = dir lastIndexOf( / ) dir = dir substring( n) out println( CWD mand succesful ) } 該命令改變當前目錄為上一層目錄 ◆ QUIT命令處理代碼如下 if(str startsWith( QUIT )) { out println( GOOD BYE ) done = true;} 該命令退出及關閉與伺服器的連接 輸出GOOD BYE

( ) 傳輸參數命令 ◆ Port命令處理代碼如下 if(str startsWith( PORT )) { out println( PORT mand successful ) int i = str length() ; int j = str lastIndexOf( ) int k = str lastIndexOf( j ) String str str ;str = ; str = ;for(int l=k+ ; lstr = str + str charAt(l) } for(int l=j+ ;l<=i;l++){ str = str + str charAt(l) } tempPort = Integer parseInt(str ) * * +Integer parseInt(str ) } 使用該命令時 客戶端必須發送客戶端用於接收數據的 位IP 地址和 位 的TCP 埠號 這些信息以 位為一組 使用十進制傳輸 中間用逗號隔開 ◆ TYPE命令處理代碼如下 if(str startsWith( TYPE )){ out println( type set ) } TYPE 命令用來完成類型設置 ( ) FTP 服務命令 ◆ RETR (RETEIEVE) 和 STORE (STORE)命令處理的代碼 if(str startsWith( RETR )){ out println( Binary data connection ) str = str substring( ) str = str trim() RandomAccessFile outFile = newRandomAccessFile(dir+ / +str r ) Socket tempSocket = new Socket(host tempPort) OutputStream outSocket= tempSocket getOutputStream() byte byteBuffer[]= new byte[ ]; int amount; try{ while((amount = outFile read(byteBuffer)) != ){

outSocket write(byteBuffer amount) } outSocket close() out println( transfer plete ) outFile close() tempSocket close() } catch(IOException e){} } if(str startsWith( STOR )){ out println( Binary data connection ) str = str substring( ) str = str trim() RandomAccessFile inFile = newRandomAccessFile(dir+ / +str rw ) Socket tempSocket = new Socket(host tempPort) InputStream inSocket= tempSocket getInputStream() byte byteBuffer[] = new byte[ ]; int amount; try{ while((amount =inSocket read(byteBuffer) )!= ){ inFile write(byteBuffer amount) } inSocket close() out println( transfer plete ) inFile close() tempSocket close() } catch(IOException e) {} } 文件傳輸命令包括從伺服器中獲得文件RETR和向伺服器中發送文件STOR 這兩個命令的處理非常類似 處理RETR命令時 首先得到用戶要獲得的文件的名稱 根據名稱創建一個文件輸入流 然後和客戶端建立臨時套接字連接 並得到一個輸出流 隨後 將文件輸入流中的數據讀出並藉助於套接字輸出流發送到客戶端 傳輸完畢以後 關閉流和臨時套接字 STOR 命令的處理也是同樣的過程 只是方向正好相反 ◆ DELE (DELETE)命令處理代碼如下 if(str startsWith( DELE )){ str = str substring( ) str = str trim() File file = new File(dir str) boolean del = file delete() out println( delete mand successful ) } DELE 命令用於刪除伺服器上的指定文件 ◆ LIST命令處理代碼如下 if(str startsWith( LIST )) { try{ out println( ASCII data ) Socket tempSocket = new Socket(host tempPort) PrintWriter out = new PrintWriter(tempSocket getOutputStream() true) File file = new File(dir) String[] dirStructure = new String[ ]; dirStructure= file list() String strType= ; for(int i= ;iif( dirStructure[i] indexOf( ) == ) { strType = d ;} else{ strType = ;} out println(strType+dirStructure[i]) } tempSocket close() out println( transfer plete ) } catch(IOException e) {} LIST 命令用於向客戶端返回伺服器中工作目錄下的目錄結構 包括文件和目錄的列表 處理這個命令時 先創建一個臨時的套接字向客戶端發送目錄信息 這個套接字的目的埠號預設為 然後為當前工作目錄創建File 對象 利用該對象的list()方法得到一個包含該目錄下所有文件和子目錄名稱的字元串數組 然後根據名稱中是否含有文件名中特有的 來區別目錄和文件 最後 將得到的名稱數組通過臨時套接字發送到客戶端 lishixin/Article/program/Java/hx/201311/26847

⑷ 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;
}

}

⑸ 怎麼用java代碼創建ftp用戶和密碼

直接用你的send輸出用戶名和密碼唄
或者根據ftp
server給你的提示,給server返回用戶名,密碼.
記得這些提示ftp協議上都有寫清楚啊.
另外ftp是要開另外一殲耐個埠傳數據的,一個socket不夠啊.
安全不安全,不全在於氏裂春代碼怎麼寫,更主要的是協議怎麼定.ftp本身就是個明文傳源缺遞的協議,誰實現的都不安全啊.
要安全,用ftps吧.
再說shell也可以完成這些功能的:)

⑹ java遠程創建文件夾與文件

兩種思路返爛:
1。直接用FILE類,但是有許可權的問題。你要保證你登陸本地的帳戶在遠碼世渣程電腦上也存在。
2。通過流傳遲悄遞過去,可以參考JAR包-FILEUPLOAD。

⑺ Java的ftp操作方法有哪幾種

FTP(File Transfer Protocol)是 Internet 上用來傳送文件的協議(文件傳輸協議)。它是為了我們能夠在 Internet 上互相傳送文件而制定的的文件傳送標准,規定了 Internet 上文件如何傳送。也就是說,通過 FTP 協議,我們就可以跟 Internet 上的 FTP 伺服器進行文件的上傳(Upload)或下載(Download)等動作。

和其他 Internet 應用一樣,FTP 也是依賴於客戶程序/伺服器關系的概念。在 Internet 上有一些網站,它們依照 FTP 協議提供服務,讓網友們進行文件的存取,這些網站就是 FTP 伺服器。網上的用戶要連上 FTP 伺服器,就要用到 FPT 的客戶端軟體,通常 Windows 都有「ftp」命令,這實際就是一個命令行的 FTP 客戶程序,另外常用的 FTP 客戶程序還有 CuteFTP、Ws_FTP、FTP Explorer等。

要連上 FTP 伺服器(即「登陸」),必須要有該 FTP 伺服器的帳號。如果是該伺服器主機的注冊客戶,你將會有一個 FTP 登陸帳號和密碼,就憑這個帳號密碼連上該伺服器。但 Internet 上有很大一部分 FTP 伺服器被稱為「匿名」(Anonymous)FTP 伺服器。這類伺服器的目的是向公眾提供文件拷貝服務,因此,不要求用戶事先在該伺服器進行登記注冊。

Anonymous(匿名文件傳輸)能夠使用戶與遠程主機建立連接並以匿名身份從遠程主機上拷貝文件,而不必是該遠程主機的注冊用戶。用戶使用特殊的用戶名「anonymous」和「guest」就可有限制地訪問遠程主機上公開的文件。現在許多系統要求用戶將Emai1地址作為口令,以便更好地對訪問進行跟綜。出於安全的目的,大部分匿名FTP主機一般只允許遠程用戶下載(download)文件,而不允許上載(upload)文件。也就是說,用戶只能從匿名FTP主機拷貝需要的文件而不能把文件拷貝到匿名FTP主機。另外,匿名FTP主機還採用了其他一些保護措施以保護自己的文件不至於被用戶修改和刪除,並防止計算機病毒的侵入。在具有圖形用戶界面的 WorldWild Web環境於1995年開始普及以前,匿名FTP一直是Internet上獲取信息資源的最主要方式,在Internet成千上萬的匿名PTP主機中存儲著無以計數的文件,這些文件包含了各種各樣的信息,數據和軟體。 人們只要知道特定信息資源的主機地址, 就可以用匿名FTP登錄獲取所需的信息資料。雖然目前使用WWW環境已取代匿名FTP成為最主要的信息查詢方式,但是匿名FTP仍是 Internet上傳輸分發軟體的一種基本方法

⑻ 如何用Java實現FTP伺服器

在主函數中,完成伺服器埠的偵聽和服務線程的創建。我們利用一個靜態字元串變數initDir 來保存伺服器線程運行時所在的工作目錄。伺服器的初始工作目錄是由程序運行時用戶輸入的,預設為C盤的根目錄。
具體的代碼如下:
public class ftpServer extends Thread{
private Socket socketClient;
private int counter;
private static String initDir;
public static void main(String[] args){
if(args.length != 0) {
initDir = args[0];
}else{ initDir = "c:";}
int i = 1;
try{
System.out.println("ftp server started!");
//監聽21號埠
ServerSocket s = new ServerSocket(21);
for(;;){
//接受客戶端請求
Socket incoming = s.accept();
//創建服務線程
new ftpServer(incoming,i).start();
i++;
}
}catch(Exception e){}
}

⑼ 怎麼用java實現ftp的登陸

/**
*依賴commons-net-3.4.jar,commons-io-2.4.jar
*/
publicclassFtpUtils{
/**
*上傳
*@paramhostFTP地址
*@paramport埠ftp默認22,sftp默認23
*@paramuserftp用戶名
*@parampwdftp密碼
*@paramdestPathFTP文件保存路徑
*@paramfileNameftp保存文件名稱
*@paramfile需要上傳的文件
*/
publicstaticvoipload(Stringhost,intport,Stringuser,Stringpwd,StringdestPath,StringfileName,Filefile){
FTPClientftp=null;
InputStreamfis=null;
try{
//1.建立連接
ftp=newFTPClient();
ftp.connect(host,port);
//2.驗證連接地址
intreply=ftp.getReplyCode();
if(FTPReply.isPositiveCompletion(reply)){
ftp.disconnect();
return;
}
//3.登錄
ftp.login(user,pwd);
//設置上傳路徑、緩存、字元集、文件類型等
ftp.changeWorkingDirectory(destPath);
ftp.setBufferSize(1024);
ftp.setControlEncoding("UTF-8");
ftp.setFileType(FTP.BINARY_FILE_TYPE);
//4.上傳
fis=newFileInputStream(file);
ftp.storeFile(fileName,fis);
}catch(SocketExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
IOUtils.closeQuietly(fis);
try{
if(ftp.isAvailable()){
ftp.logout();
}
if(ftp.isConnected()){
ftp.disconnect();
}
//刪除上傳臨時文件
if(null!=file&&file.exists()){
file.delete();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}