首先導入包
import org.apache.commons.NET.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
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傳送到遠程計算機。
案例:
public FTPClient ftp = new FTPClient(); // 實例化ftp客戶端對象。
/*******************登陸***********************/
// 開始讀取 就去連接FTP服務器
if (ftp.isConnected() == false)
{
try
{
ftp.connect(host_ip);// 連接 Ftp host_ip FTP服務器ip
try
{
ftp.login(username, password);// 登陸 login ()方法登陸ftp
ftp.setFileType(FTPClient.ASCII_FILE_TYPE);// 設置文件類型setFileType()設置ftp文件類型
} catch (Exception e1)
{
log.error(“faile to load!!!!”);
}
} catch (SocketException e1)
{
log.error(“建立連接FTP連接失敗”);
} catch (IOException e1)
{
log.error(“IO異常FTP.txt讀取失敗”);
}
}
/**************下載文件***************************/
public void downloadFiles()
{
// 進入FTP服務器工作目錄
ftp.changeWorkingDirectory(ftp.printWorkingDirectory()+ remote_dir); // remote_dir FTP遠程文件目錄
// 獲得遠程ftp目錄下的文件列表
FTPFile[] fileList = ftp.listFiles(“.”); // . 號可替換成文件指定ftp目錄。獲取FTPfile文件列表。注意:文件列表包含文件夾及文件
String[] files = ftp.listNames(); // 獲取FTP服務器文件名稱列表。注意:文件列表包含文件夾及文件的名稱。
/*
fileList[0].getGroup(); // 文件所屬組 ,對應有set
fileList[0].getName(); // 文件名稱, setName(“”)重命名
fileList[0].getSize(); // 文件大小 返回long數據類型
fileList[0].getTimestamp().getTime(); //文件最後修改時間
fileList[0].getType(); //文件類型
fileList[0].getUser(); //文件所屬用戶
fileList[0].isDirectory(); // 文件是不是文件夾
fileList[0].isFile(); //判斷是不是 文件
fileList[0].isSymbolicLink(); // ???
fileList[0].isUnknown(); // ?、、
fileList[0].DIRECTORY_TYPE; //屬性,文件夾類型 返回int型
fileList[0].FILE_TYPE; // 屬性, 文件類型, 返回int型
fileList[0].GROUP_ACCESS; //組, 返回int型
*/
//下載指定文件的時候,要判斷指定文件的名稱,比如下載,AA.TXT文件
//遍歷獲取的FTP文件名稱列表
for(int i ; i < fileList.length (標註: 或者files.length ); i ++ )
{
//判斷文件名是否包含AA.txt的。注意:在 Linux裏 fileList 對象獲取不到length屬性。必須通過files屬性獲取。判斷文件名稱列表也必須從files數組中獲取。
if(fileList[i].getName().indexOf(“AA.txt”) != -1)
{
File localfile = new File(local_dir+”/”+fileList[i].getName());
OutPutStream ops = FileOutputStream(localFile);
ftp.retrieveFile(fileList[i].getName(), ops); //將FTP上指定文件名稱的文件,下載到本地指定輸出流的文件夾中。
ops.close();
}
}
}
/******************上傳指定文件***********************/
/**
* Description: 向FTP服務器上傳文件
* @Version1.0 Jul 27, 2008 4:31:09 PM by 崔紅保([email protected])創建
* @param url FTP服務器hostname
* @param port FTP服務器端口
* @param username FTP登錄賬號
* @param password FTP登錄密碼
* @param path FTP服務器保存目錄
* @param filename 上傳到FTP服務器上的文件名
* @param input 輸入流
* @return 成功返回true,否則返回false
*/
public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(url, port);//連接FTP服務器
//如果採用默認端口,可以使用ftp.connect(url)的方式直接連接FTP服務器
ftp.login(username, password);//登錄
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(path);
ftp.storeFile(filename, input);
input.close();
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
@Test
public void testUpLoadFromDisk(){
try {
FileInputStream in=new FileInputStream(new File(“D:/test.txt”));
boolean flag = uploadFile(“127.0.0.1”, 21, “test”, “test”, “D:/ftp”, “test.txt”, in);
System.out.println(flag);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
案例一:
用apache FTP client實現FTP客戶端–支持斷點續傳和中文文件
利用org.apache.commons.Net.ftp包實現一個簡單的ftp客戶端實用類。主要實現一下功能
1.支持上傳下載。支持斷點續傳
2.支持進度彙報
3.支持對於中文目錄及中文文件創建的支持。
枚舉類UploadStatus代碼
- 1. public enum UploadStatus {
- 2. Create_Directory_Fail, //遠程服務器相應目錄創建失敗
- 3. Create_Directory_Success, //遠程服務器闖將目錄成功
- 4. Upload_New_File_Success, //上傳新文件成功
- 5. Upload_New_File_Failed, //上傳新文件失敗
- 6. File_Exits, //文件已經存在
- 7. Remote_Bigger_Local, //遠程文件大於本地文件
- 8. Upload_From_Break_Success, //斷點續傳成功
- 9. Upload_From_Break_Failed, //斷點續傳失敗
- 10. Delete_Remote_Faild; //刪除遠程文件失敗
- 11. }
枚舉類DownloadStatus代碼
- 1. public enum DownloadStatus {
- 2. Remote_File_Noexist, //遠程文件不存在
- 3. Local_Bigger_Remote, //本地文件大於遠程文件
- 4. Download_From_Break_Success, //斷點下載文件成功
- 5. Download_From_Break_Failed, //斷點下載文件失敗
- 6. Download_New_Success, //全新下載文件成功
- 7. Download_New_Failed; //全新下載文件失敗
- 8. }
核心FTP代碼
- 核心FTP代碼
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.io.PrintWriter;
- import java.io.RandomAccessFile;
- import open.mis.data.DownloadStatus;
- import open.mis.data.UploadStatus;
- import org.apache.commons.net.PrintCommandListener;
- 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;
- /**
- * 支持斷點續傳的FTP實用類
- * @author BenZhou
- * @version 0.1 實現基本斷點上傳下載
- * @version 0.2 實現上傳下載進度彙報
- * @version 0.3 實現中文目錄創建及中文文件創建,添加對於中文的支持
- */
- public class ContinueFTP {
- public FTPClient ftpClient = new FTPClient();
- public ContinueFTP(){
- //設置將過程中使用到的命令輸出到控制檯
- this.ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
- }
- /**
- * 連接到FTP服務器
- * @param hostname 主機名
- * @param port 端口
- * @param username 用戶名
- * @param password 密碼
- * @return 是否連接成功
- * @throws IOException
- */
- public boolean connect(String hostname,int port,String username,String password) throws IOException{
- ftpClient.connect(hostname, port);
- ftpClient.setControlEncoding(”GBK”);
- if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
- if(ftpClient.login(username, password)){
- return true;
- }
- }
- disconnect();
- return false;
- }
- /**
- * 從FTP服務器上下載文件,支持斷點續傳,上傳百分比彙報
- * @param remote 遠程文件路徑
- * @param local 本地文件路徑
- * @return 上傳的狀態
- * @throws IOException
- */
- public DownloadStatus download(String remote,String local) throws IOException{
- //設置被動模式
- ftpClient.enterLocalPassiveMode();
- //設置以二進制方式傳輸
- ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
- DownloadStatus result;
- //檢查遠程文件是否存在
- FTPFile[] files = ftpClient.listFiles(new String(remote.getBytes(“GBK”),“iso-8859-1”));
- if(files.length != 1){
- System.out.println(“遠程文件不存在”);
- return DownloadStatus.Remote_File_Noexist;
- }
- long lRemoteSize = files[0].getSize();
- File f = new File(local);
- //本地存在文件,進行斷點下載
- if(f.exists()){
- long localSize = f.length();
- //判斷本地文件大小是否大於遠程文件大小
- if(localSize >= lRemoteSize){
- System.out.println(“本地文件大於遠程文件,下載中止”);
- return DownloadStatus.Local_Bigger_Remote;
- }
- //進行斷點續傳,並記錄狀態
- FileOutputStream out = new FileOutputStream(f,true);
- ftpClient.setRestartOffset(localSize);
- InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes(“GBK”),“iso-8859-1”));
- byte[] bytes = new byte[1024];
- long step = lRemoteSize /100;
- long process=localSize /step;
- int c;
- while((c = in.read(bytes))!= -1){
- out.write(bytes,0,c);
- localSize+=c;
- long nowProcess = localSize /step;
- if(nowProcess > process){
- process = nowProcess;
- if(process % 10 == 0)
- System.out.println(“下載進度:”+process);
- //TODO 更新文件下載進度,值存放在process變量中
- }
- }
- in.close();
- out.close();
- boolean isDo = ftpClient.completePendingCommand();
- if(isDo){
- result = DownloadStatus.Download_From_Break_Success;
- }else {
- result = DownloadStatus.Download_From_Break_Failed;
- }
- }else {
- OutputStream out = new FileOutputStream(f);
- InputStream in= ftpClient.retrieveFileStream(new String(remote.getBytes(“GBK”),“iso-8859-1”));
- byte[] bytes = new byte[1024];
- long step = lRemoteSize /100;
- long process=0;
- long localSize = 0L;
- int c;
- while((c = in.read(bytes))!= -1){
- out.write(bytes, 0, c);
- localSize+=c;
- long nowProcess = localSize /step;
- if(nowProcess > process){
- process = nowProcess;
- if(process % 10 == 0)
- System.out.println(“下載進度:”+process);
- //TODO 更新文件下載進度,值存放在process變量中
- }
- }
- in.close();
- out.close();
- boolean upNewStatus = ftpClient.completePendingCommand();
- if(upNewStatus){
- result = DownloadStatus.Download_New_Success;
- }else {
- result = DownloadStatus.Download_New_Failed;
- }
- }
- return result;
- }
- /**
- * 上傳文件到FTP服務器,支持斷點續傳
- * @param local 本地文件名稱,絕對路徑
- * @param remote 遠程文件路徑,使用/home/directory1/subdirectory/file.ext 按照Linux上的路徑指定方式,支持多級目錄嵌套,支持遞歸創建不存在的目錄結構
- * @return 上傳結果
- * @throws IOException
- */
- public UploadStatus upload(String local,String remote) throws IOException{
- //設置PassiveMode傳輸
- ftpClient.enterLocalPassiveMode();
- //設置以二進制流的方式傳輸
- ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
- ftpClient.setControlEncoding(”GBK”);
- UploadStatus result;
- //對遠程目錄的處理
- String remoteFileName = remote;
- if(remote.contains(“/”)){
- remoteFileName = remote.substring(remote.lastIndexOf(”/”)+1);
- //創建服務器遠程目錄結構,創建失敗直接返回
- if(CreateDirecroty(remote, ftpClient)==UploadStatus.Create_Directory_Fail){
- return UploadStatus.Create_Directory_Fail;
- }
- }
- //檢查遠程是否存在文件
- FTPFile[] files = ftpClient.listFiles(new String(remoteFileName.getBytes(“GBK”),“iso-8859-1”));
- if(files.length == 1){
- long remoteSize = files[0].getSize();
- File f = new File(local);
- long localSize = f.length();
- if(remoteSize==localSize){
- return UploadStatus.File_Exits;
- }else if(remoteSize > localSize){
- return UploadStatus.Remote_Bigger_Local;
- }
- //嘗試移動文件內讀取指針,實現斷點續傳
- result = uploadFile(remoteFileName, f, ftpClient, remoteSize);
- //如果斷點續傳沒有成功,則刪除服務器上文件,重新上傳
- if(result == UploadStatus.Upload_From_Break_Failed){
- if(!ftpClient.deleteFile(remoteFileName)){
- return UploadStatus.Delete_Remote_Faild;
- }
- result = uploadFile(remoteFileName, f, ftpClient, 0);
- }
- }else {
- result = uploadFile(remoteFileName, new File(local), ftpClient, 0);
- }
- return result;
- }
- /**
- * 斷開與遠程服務器的連接
- * @throws IOException
- */
- public void disconnect() throws IOException{
- if(ftpClient.isConnected()){
- ftpClient.disconnect();
- }
- }
- /**
- * 遞歸創建遠程服務器目錄
- * @param remote 遠程服務器文件絕對路徑
- * @param ftpClient FTPClient對象
- * @return 目錄創建是否成功
- * @throws IOException
- */
- public UploadStatus CreateDirecroty(String remote,FTPClient ftpClient) throws IOException{
- UploadStatus status = UploadStatus.Create_Directory_Success;
- String directory = remote.substring(0,remote.lastIndexOf(”/”)+1);
- if(!directory.equalsIgnoreCase(“/”)&&!ftpClient.changeWorkingDirectory(new String(directory.getBytes(“GBK”),“iso-8859-1”))){
- //如果遠程目錄不存在,則遞歸創建遠程服務器目錄
- int start=0;
- int end = 0;
- if(directory.startsWith(“/”)){
- start = 1;
- }else{
- start = 0;
- }
- end = directory.indexOf(”/”,start);
- while(true){
- String subDirectory = new String(remote.substring(start,end).getBytes(“GBK”),“iso-8859-1”);
- if(!ftpClient.changeWorkingDirectory(subDirectory)){
- if(ftpClient.makeDirectory(subDirectory)){
- ftpClient.changeWorkingDirectory(subDirectory);
- }else {
- System.out.println(“創建目錄失敗”);
- return UploadStatus.Create_Directory_Fail;
- }
- }
- start = end + 1;
- end = directory.indexOf(”/”,start);
- //檢查所有目錄是否創建完畢
- if(end <= start){
- break;
- }
- }
- }
- return status;
- }
- /**
- * 上傳文件到服務器,新上傳和斷點續傳
- * @param remoteFile 遠程文件名,在上傳之前已經將服務器工作目錄做了改變
- * @param localFile 本地文件File句柄,絕對路徑
- * @param processStep 需要顯示的處理進度步進值
- * @param ftpClient FTPClient引用
- * @return
- * @throws IOException
- */
- public UploadStatus uploadFile(String remoteFile,File localFile,FTPClient ftpClient,long remoteSize) throws IOException{
- UploadStatus status;
- //顯示進度的上傳
- long step = localFile.length() / 100;
- long process = 0;
- long localreadbytes = 0L;
- RandomAccessFile raf = new RandomAccessFile(localFile,“r”);
- OutputStream out = ftpClient.appendFileStream(new String(remoteFile.getBytes(“GBK”),“iso-8859-1”));
- //斷點續傳
- if(remoteSize>0){
- ftpClient.setRestartOffset(remoteSize);
- process = remoteSize /step;
- raf.seek(remoteSize);
- localreadbytes = remoteSize;
- }
- byte[] bytes = new byte[1024];
- int c;
- while((c = raf.read(bytes))!= -1){
- out.write(bytes,0,c);
- localreadbytes+=c;
- if(localreadbytes / step != process){
- process = localreadbytes / step;
- System.out.println(“上傳進度:” + process);
- //TODO 彙報上傳狀態
- }
- }
- out.flush();
- raf.close();
- out.close();
- boolean result =ftpClient.completePendingCommand();
- if(remoteSize > 0){
- status = result?UploadStatus.Upload_From_Break_Success:UploadStatus.Upload_From_Break_Failed;
- }else {
- status = result?UploadStatus.Upload_New_File_Success:UploadStatus.Upload_New_File_Failed;
- }
- return status;
- }
- public static void main(String[] args) {
- ContinueFTP myFtp = new ContinueFTP();
- try {
- myFtp.connect(”192.168.21.181”, 21, “nid”, “123”);
- // myFtp.ftpClient.makeDirectory(new String(“電視劇”.getBytes(“GBK”),”iso-8859-1”));
- // myFtp.ftpClient.changeWorkingDirectory(new String(“電視劇”.getBytes(“GBK”),”iso-8859-1”));
- // myFtp.ftpClient.makeDirectory(new String(“走西口”.getBytes(“GBK”),”iso-8859-1”));
- // System.out.println(myFtp.upload(“E://yw.flv”, ”/yw.flv”,5));
- // System.out.println(myFtp.upload(“E://走西口24.mp4”,”/央視走西口/新浪網/走西口24.mp4”));
- System.out.println(myFtp.download(“/央視走西口/新浪網/走西口24.mp4”, “E://走西口242.mp4”));
- myFtp.disconnect();
- } catch (IOException e) {
- System.out.println(“連接FTP出錯:”+e.getMessage());
- }
- }
- }
案例二:
FTP客戶端
package cm;
import Java.io.File;
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
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;
public class FtpHelper {
private FTPClient ftpClient = new FTPClient();
/**
* 連接到FTP服務器
*
* @param hostname
* 主機名
* @param port
* 端口
* @param username
* 用戶名
* @param password
* 密碼
* @return 是否連接成功
* @throws IOException
*/
public boolean connect(String hostname, int port, String username,
String password) throws IOException {
ftpClient.connect(hostname, port);
ftpClient.setControlEncoding(“GBK”);
if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
if (ftpClient.login(username, password)) {
return true;
}
}
disconnect();
return false;
}
/**
* 從FTP服務器上下載文件,支持斷點續傳,上傳百分比彙報
*
* @param remote
* 遠程文件路徑
* @param local
* 本地文件路徑
* @return 上傳的狀態
* @throws IOException
*/
public DownloadStatus download(String remote, String local)
throws IOException {
// 設置被動模式
ftpClient.enterLocalPassiveMode();
// 設置以二進制方式傳輸
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
DownloadStatus result;
// 檢查遠程文件是否存在
FTPFile[] files = ftpClient.listFiles(new String(
remote.getBytes(“GBK”), “iso-8859-1”));
if (files.length != 1) {
System.out.println(“遠程文件不存在”);
return DownloadStatus.Remote_File_Noexist;
}
long lRemoteSize = files[0].getSize();
File f = new File(local);
// 本地存在文件,進行斷點下載
if (f.exists()) {
long localSize = f.length();
// 判斷本地文件大小是否大於遠程文件大小
if (localSize >= lRemoteSize) {
System.out.println(“本地文件大於遠程文件,下載中止”);
return DownloadStatus.Local_Bigger_Remote;
}
// 進行斷點續傳,並記錄狀態
FileOutputStream out = new FileOutputStream(f, true);
ftpClient.setRestartOffset(localSize);
InputStream in = ftpClient.retrieveFileStream(new String(remote
.getBytes(“GBK”), “iso-8859-1”));
byte[] bytes = new byte[1024];
long step = lRemoteSize / 100;
long process = localSize / step;
int c;
while ((c = in.read(bytes)) != -1) {
out.write(bytes, 0, c);
localSize += c;
long nowProcess = localSize / step;
if (nowProcess > process) {
process = nowProcess;
if (process % 10 == 0)
System.out.println(“下載進度:” + process);
// TODO 更新文件下載進度,值存放在process變量中
}
}
in.close();
out.close();
boolean isDo = ftpClient.completePendingCommand();
if (isDo) {
result = DownloadStatus.Download_From_Break_Success;
} else {
result = DownloadStatus.Download_From_Break_Failed;
}
} else {
OutputStream out = new FileOutputStream(f);
InputStream in = ftpClient.retrieveFileStream(new String(remote
.getBytes(“GBK”), “iso-8859-1”));
byte[] bytes = new byte[1024];
long step = lRemoteSize / 100;
long process = 0;
long localSize = 0L;
int c;
while ((c = in.read(bytes)) != -1) {
out.write(bytes, 0, c);
localSize += c;
long nowProcess = localSize / step;
if (nowProcess > process) {
process = nowProcess;
if (process % 10 == 0)
System.out.println(“下載進度:” + process);
// TODO 更新文件下載進度,值存放在process變量中
}
}
in.close();
out.close();
boolean upNewStatus = ftpClient.completePendingCommand();
if (upNewStatus) {
result = DownloadStatus.Download_New_Success;
} else {
result = DownloadStatus.Download_New_Failed;
}
}
return result;
}
/**
* 上傳文件到FTP服務器,支持斷點續傳
*
* @param local
* 本地文件名稱,絕對路徑
* @param remote
* 遠程文件路徑,使用/home/directory1/subdirectory/file.ext
* 按照linux上的路徑指定方式,支持多級目錄嵌套,支持遞歸創建不存在的目錄結構
* @return 上傳結果
* @throws IOException
*/
public UploadStatus upload(String local, String remote) throws IOException {
// 設置PassiveMode傳輸
ftpClient.enterLocalPassiveMode();
// 設置以二進制流的方式傳輸
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setControlEncoding(“GBK”);
UploadStatus result;
// 對遠程目錄的處理
String remoteFileName = remote;
if (remote.contains(“/”)) {
remoteFileName = remote.substring(remote.lastIndexOf(“/”) + 1);
// 創建服務器遠程目錄結構,創建失敗直接返回
if (createDirecroty(remote, ftpClient) == UploadStatus.Create_Directory_Fail) {
return UploadStatus.Create_Directory_Fail;
}
}
//ftpClient.feat();
// System.out.println( ftpClient.getReply());
// System.out.println( ftpClient.acct(null));
// System.out.println(ftpClient.getReplyCode());
// System.out.println(ftpClient.getReplyString());
// 檢查遠程是否存在文件
FTPFile[] files = ftpClient.listFiles(new String(remoteFileName
.getBytes(“GBK”), “iso-8859-1”));
if (files.length == 1) {
long remoteSize = files[0].getSize();
File f = new File(local);
long localSize = f.length();
if (remoteSize == localSize) { // 文件存在
return UploadStatus.File_Exits;
} else if (remoteSize > localSize) {
return UploadStatus.Remote_Bigger_Local;
}
// 嘗試移動文件內讀取指針,實現斷點續傳
result = uploadFile(remoteFileName, f, ftpClient, remoteSize);
// 如果斷點續傳沒有成功,則刪除服務器上文件,重新上傳
if (result == UploadStatus.Upload_From_Break_Failed) {
if (!ftpClient.deleteFile(remoteFileName)) {
return UploadStatus.Delete_Remote_Faild;
}
result = uploadFile(remoteFileName, f, ftpClient, 0);
}
} else {
result = uploadFile(remoteFileName, new File(local), ftpClient, 0);
}
return result;
}
/**
* 斷開與遠程服務器的連接
*
* @throws IOException
*/
public void disconnect() throws IOException {
if (ftpClient.isConnected()) {
ftpClient.disconnect();
}
}
/**
* 遞歸創建遠程服務器目錄
*
* @param remote
* 遠程服務器文件絕對路徑
* @param ftpClient
* FTPClient對象
* @return 目錄創建是否成功
* @throws IOException
*/
public UploadStatus createDirecroty(String remote, FTPClient ftpClient)
throws IOException {
UploadStatus status = UploadStatus.Create_Directory_Success;
String directory = remote.substring(0, remote.lastIndexOf(“/”) + 1);
if (!directory.equalsIgnoreCase(“/”)
&& !ftpClient.changeWorkingDirectory(new String(directory
.getBytes(“GBK”), “iso-8859-1”))) {
// 如果遠程目錄不存在,則遞歸創建遠程服務器目錄
int start = 0;
int end = 0;
if (directory.startsWith(“/”)) {
start = 1;
} else {
start = 0;
}
end = directory.indexOf(“/”, start);
while (true) {
String subDirectory = new String(remote.substring(start, end)
.getBytes(“GBK”), “iso-8859-1”);
if (!ftpClient.changeWorkingDirectory(subDirectory)) {
if (ftpClient.makeDirectory(subDirectory)) {
ftpClient.changeWorkingDirectory(subDirectory);
} else {
System.out.println(“創建目錄失敗”);
return UploadStatus.Create_Directory_Fail;
}
}
start = end + 1;
end = directory.indexOf(“/”, start);
// 檢查所有目錄是否創建完畢
if (end <= start) {
break;
}
}
}
return status;
}
/**
* 上傳文件到服務器,新上傳和斷點續傳
*
* @param remoteFile
* 遠程文件名,在上傳之前已經將服務器工作目錄做了改變
* @param localFile
* 本地文件File句柄,絕對路徑
* @param processStep
* 需要顯示的處理進度步進值
* @param ftpClient
* FTPClient引用
* @return
* @throws IOException
*/
public UploadStatus uploadFile(String remoteFile, File localFile,
FTPClient ftpClient, long remoteSize) throws IOException {
UploadStatus status;
// 顯示進度的上傳
long step = localFile.length() / 100;
long process = 0;
long localreadbytes = 0L;
RandomAccessFile raf = new RandomAccessFile(localFile, “r”);
String remote = new String(remoteFile.getBytes(“GBK”), “iso-8859-1”);
OutputStream out = ftpClient.appendFileStream(remote);
if(out==null)
{
String message = ftpClient.getReplyString();
throw new RuntimeException(message);
}
// 斷點續傳
if (remoteSize > 0) {
ftpClient.setRestartOffset(remoteSize);
process = remoteSize / step;
raf.seek(remoteSize);
localreadbytes = remoteSize;
}
byte[] bytes = new byte[1024];
int c;
while ((c = raf.read(bytes)) != -1) {
out.write(bytes, 0, c);
localreadbytes += c;
if (localreadbytes / step != process) {
process = localreadbytes / step;
System.out.println(“上傳進度:” + process);
// TODO 彙報上傳狀態
}
}
out.flush();
raf.close();
out.close();
boolean result = ftpClient.completePendingCommand();
if (remoteSize > 0) {
status = result ? UploadStatus.Upload_From_Break_Success
: UploadStatus.Upload_From_Break_Failed;
} else {
status = result ? UploadStatus.Upload_New_File_Success
: UploadStatus.Upload_New_File_Failed;
}
return status;
}
/**
* 獲取指定目錄下的文件名稱列表
* @author HQQW510_64
* @param currentDir 需要獲取其子目錄的當前目錄名稱
* @return 返回子目錄字符串數組
*/
public String[] GetFileNames(String currentDir) {
String[] dirs = null;
try {
if(currentDir==null)
dirs = ftpClient.listNames();
else
dirs = ftpClient.listNames(currentDir);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dirs;
}
/**
* 獲取指定目錄下的文件與目錄信息集合
* @param currentDir 指定的當前目錄
* @return 返回的文件集合
*/
public FTPFile[] GetDirAndFilesInfo(String currentDir)
{
FTPFile[] files=null;
try
{
if(currentDir==null)
files=ftpClient.listFiles();
else
files = ftpClient.listFiles(currentDir);
}
catch(IOException ex)
{
// TODO Auto-generated catch block
ex.printStackTrace();
}
return files;
}
}
案例三
JAVA中使用FTPClient上傳下載
在JAVA程序中,經常需要和FTP打交道,比如向FTP服務器上傳文件、下載文件,本文簡單介紹如何利用jakarta commons中的FTPClient(在commons-net包中)實現上傳下載文件。
一、上傳文件
原理就不介紹了,大家直接看代碼吧
- /**
- * Description: 向FTP服務器上傳文件
- * @Version1.0 Jul 27, 2008 4:31:09 PM by 崔紅保([email protected])創建
- * @param url FTP服務器hostname
- * @param port FTP服務器端口
- * @param username FTP登錄賬號
- * @param password FTP登錄密碼
- * @param path FTP服務器保存目錄
- * @param filename 上傳到FTP服務器上的文件名
- * @param input 輸入流
- * @return 成功返回true,否則返回false
- */
- public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {
- boolean success = false;
- FTPClient ftp = new FTPClient();
- try {
- int reply;
- ftp.connect(url, port);//連接FTP服務器
- //如果採用默認端口,可以使用ftp.connect(url)的方式直接連接FTP服務器
- ftp.login(username, password);//登錄
- reply = ftp.getReplyCode();
- if (!FTPReply.isPositiveCompletion(reply)) {
- ftp.disconnect();
- return success;
- }
- ftp.changeWorkingDirectory(path);
- ftp.storeFile(filename, input);
- input.close();
- ftp.logout();
- success = true;
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (ftp.isConnected()) {
- try {
- ftp.disconnect();
- } catch (IOException ioe) {
- }
- }
- }
- return success;
- }<pre></pre>
下面我們寫兩個小例子:
1.將本地文件上傳到FTP服務器上,代碼如下:
- @Test
- public void testUpLoadFromDisk(){
- try {
- FileInputStream in=new FileInputStream(new File(“D:/test.txt”));
- boolean flag = uploadFile(“127.0.0.1”, 21, “test”, “test”, “D:/ftp”, “test.txt”, in);
- System.out.println(flag);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- }<pre></pre>
2.在FTP服務器上生成一個文件,並將一個字符串寫入到該文件中
- @Test
- public void testUpLoadFromString(){
- try {
- InputStream input = new ByteArrayInputStream(“test ftp”.getBytes(“utf-8”));
- boolean flag = uploadFile(“127.0.0.1”, 21, “test”, “test”, “D:/ftp”, “test.txt”, input);
- System.out.println(flag);
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- }<pre></pre>
二、下載文件
從FTP服務器下載文件的代碼也很簡單,參考如下:
- /**
- * Description: 從FTP服務器下載文件
- * @Version1.0 Jul 27, 2008 5:32:36 PM by 崔紅保([email protected])創建
- * @param url FTP服務器hostname
- * @param port FTP服務器端口
- * @param username FTP登錄賬號
- * @param password FTP登錄密碼
- * @param remotePath FTP服務器上的相對路徑
- * @param fileName 要下載的文件名
- * @param localPath 下載後保存到本地的路徑
- * @return
- */
- public static boolean downFile(String url, int port,String username, String password, String remotePath,String fileName,String localPath) {
- boolean success = false;
- FTPClient ftp = new FTPClient();
- try {
- int reply;
- ftp.connect(url, port);
- //如果採用默認端口,可以使用ftp.connect(url)的方式直接連接FTP服務器
- ftp.login(username, password);//登錄
- reply = ftp.getReplyCode();
- if (!FTPReply.isPositiveCompletion(reply)) {
- ftp.disconnect();
- return success;
- }
- ftp.changeWorkingDirectory(remotePath);//轉移到FTP服務器目錄
- FTPFile[] fs = ftp.listFiles();
- for(FTPFile ff:fs){
- if(ff.getName().equals(fileName)){
- File localFile = new File(localPath+“/”+ff.getName());
- OutputStream is = new FileOutputStream(localFile);
- ftp.retrieveFile(ff.getName(), is);
- is.close();
- }
- }
- ftp.logout();
- success = true;
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (ftp.isConnected()) {
- try {
- ftp.disconnect();
- } catch (IOException ioe) {
- }
- }
- }
- return success;
- }<pre></pre>
案例三:
- /**
- * 支持斷點續傳的FTP實用類
- *
- * @author chenxin
- * @version [版本號, 2012-5-21]
- * @see [相關類/方法]
- * @since [產品/模塊版本]
- */
- public class FtpUtils {
- private FTPClient ftpClient = null;
- private static final Logger logger = Logger.getLogger(FtpUtils.class);
- private String hostname;
- private String username;
- private String password;
- private int port;
- private static final String EPUB_DIR = “epub_file”;
- public FtpUtils()
- {
- ftpClient = new FTPClient();
- username = ServerConfig.get(”ftp/ftp-user”, “”);
- password = ServerConfig.get(”ftp/ftp-password”, “”);
- hostname = ServerConfig.get(”ftp/ftp-host”, “”);
- port = ServerConfig.getInt(”ftp/ftp-port”, 21);
- // {
- // //設置將過程中使用到的命令輸出到控制檯
- // ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
- // }
- }
- /**
- * 連接到FTP服務器
- * @param hostname 主機名
- * @param port 端口
- * @param username 用戶名
- * @param password 密碼
- * @return 是否連接成功
- * @throws IOException
- */
- public boolean connect() throws IOException{
- ftpClient.connect(hostname, port);
- ftpClient.setControlEncoding(ServerConfig.get(”ftp/ftp-charset”, “GBK”));
- if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
- if(ftpClient.login(username, password)){
- // 設置被動模式
- ftpClient.enterLocalPassiveMode();
- // 設置以二進制方式傳輸
- ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
- return true;
- }
- }
- disconnect();
- return false;
- }
- public boolean reconnect() throws IOException
- {
- disconnect();
- ftpClient.connect(hostname, port);
- ftpClient.setControlEncoding(ServerConfig.get(”ftp/ftp-charset”, “GBK”));
- if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
- if(ftpClient.login(username, password)){
- // 設置被動模式
- ftpClient.enterLocalPassiveMode();
- // 設置以二進制方式傳輸
- ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
- return true;
- }
- }
- disconnect();
- return false;
- }
- /**
- * 從FTP服務器上下載文件,上傳百分比
- * @param remote
- * @param dir
- * @param fileName
- * @return
- * @throws IOException
- * @see [類、類#方法、類#成員]
- */
- public boolean download(String remote, String dir, String fileName)
- throws IOException
- {
- File file = new File(dir + File.separator + fileName);
- // 本地存在文件
- if (file.exists())
- {
- if (logger.isDebugEnabled())
- {
- logger.debug(”File is existsed.”);
- }
- // 如果文件存在,但還未從FTP服務器上完全取下來,則需要等待
- Long initialSize = 0L;
- int i = 0;
- while (initialSize != file.length())
- {
- i++;
- initialSize = file.length();
- try
- {
- Thread.sleep(100L);
- }
- catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- }
- if (i > 1)
- {
- // 如果是剛下完的文件,則不需要再比對大小是否一致
- return true;
- }
- }
- Long localSize = file.length();
- File localDir = new File(dir);
- if (!localDir.exists())
- {
- localDir.mkdirs();
- }
- // 檢查遠程文件是否存在
- if (remote.startsWith(“/”))
- {
- remote = remote.substring(1);
- }
- if (ftpClient.listNames(remote).length <= 0)
- {
- // 文件不存在
- logger.error(”Could not find file from ftp server: ” + remote);
- return false;
- }
- // 計算遠程文件大小
- String s = ”SIZE ” + remote + “\r\n”;
- ftpClient.sendCommand(s);
- String s1 = ftpClient.getReplyString();
- Long remoteSize = Long.parseLong(s1.substring(3).trim());
- if (logger.isDebugEnabled())
- {
- logger.debug(”localsize: ” + localSize + “, remoteSize: ” + remoteSize);
- }
- if (remoteSize.equals(localSize))
- {
- if (logger.isDebugEnabled())
- {
- logger.debug(”File’s size not changed.”);
- }
- return true;
- }
- else if (localSize != 0L)
- {
- if (logger.isDebugEnabled())
- {
- logger.debug(”File’s size changed which needed re-download.”);
- }
- //遠程文件和本地文件大小不一致,則刪除本地文件
- file.delete();
- //如果是EPUB書路徑,則需要把解壓過的臨時文件也一併刪除
- if (dir.indexOf(EPUB_DIR) > 0)
- {
- deleteAll(localDir);
- }
- }
- // 重連以回到根目錄
- reconnect();
- OutputStream out = new FileOutputStream(file);
- InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes(“UTF-8”),
- ServerConfig.get(”ftp/ftp-charset”, “GBK”)));
- if (logger.isDebugEnabled())
- {
- logger.debug(”Begin to downloaded file from ftp.”);
- }
- byte[] bytes = new byte[1024];
- int count;
- while ((count = in.read(bytes)) != -1)
- {
- out.write(bytes, 0, count);
- }
- if (logger.isDebugEnabled())
- {
- logger.debug(”File has been downloaded from ftp successfully.”);
- }
- in.close();
- out.close();
- boolean upNewStatus = ftpClient.completePendingCommand();
- if (upNewStatus)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- //遞歸刪除文件夾
- private void deleteAll(File file)
- {
- if (file.isDirectory() && !ArrayUtils.isEmpty(file.list()))
- {
- for (File childFile : file.listFiles())
- {
- deleteAll(childFile);
- }
- }
- else
- {
- file.delete();
- }
- }
- /** *//**
- * 斷開與遠程服務器的連接
- * @throws IOException
- */
- public void disconnect() throws IOException{
- if(ftpClient.isConnected()){
- ftpClient.disconnect();
- }
- }
- public static void main(String[] args) {
- FtpUtils myFtp = new FtpUtils();
- try {
- myFtp.connect();
- System.out.println(myFtp.download(”/央視走西口/新浪網/走西口24.mp4”, “E:\\走西口242.mp4”, “123”));
- myFtp.disconnect();
- } catch (IOException e) {
- System.out.println(”連接FTP出錯:”+e.getMessage());
- }
- }
- //使用: 下載文件
- FtpUtils ftpUtils = new FtpUtils();
- ftpUtils.connect();
- ftpUtils.download(fileUrl, directoryPath, filename);
- ftpUtils.disconnect();
- }
/**
* 支持斷點續傳的FTP實用類
*
* @author chenxin
* @version [版本號, 2012-5-21]
* @see [相關類/方法]
* @since [產品/模塊版本]
*/
public class FtpUtils {
private FTPClient ftpClient = null;
private static final Logger logger = Logger.getLogger(FtpUtils.class);
private String hostname;
private String username;
private String password;
private int port;
private static final String EPUB_DIR = "epub_file";
public FtpUtils()
{
ftpClient = new FTPClient();
username = ServerConfig.get("ftp/ftp-user", "");
password = ServerConfig.get("ftp/ftp-password", "");
hostname = ServerConfig.get("ftp/ftp-host", "");
port = ServerConfig.getInt("ftp/ftp-port", 21);
// {
// //設置將過程中使用到的命令輸出到控制檯
// ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
// }
}
/**
* 連接到FTP服務器
* @param hostname 主機名
* @param port 端口
* @param username 用戶名
* @param password 密碼
* @return 是否連接成功
* @throws IOException
*/
public boolean connect() throws IOException{
ftpClient.connect(hostname, port);
ftpClient.setControlEncoding(ServerConfig.get("ftp/ftp-charset", "GBK"));
if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
if(ftpClient.login(username, password)){
// 設置被動模式
ftpClient.enterLocalPassiveMode();
// 設置以二進制方式傳輸
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
return true;
}
}
disconnect();
return false;
}
public boolean reconnect() throws IOException
{
disconnect();
ftpClient.connect(hostname, port);
ftpClient.setControlEncoding(ServerConfig.get("ftp/ftp-charset", "GBK"));
if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
if(ftpClient.login(username, password)){
// 設置被動模式
ftpClient.enterLocalPassiveMode();
// 設置以二進制方式傳輸
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
return true;
}
}
disconnect();
return false;
}
/**
* 從FTP服務器上下載文件,上傳百分比
* @param remote
* @param dir
* @param fileName
* @return
* @throws IOException
* @see [類、類#方法、類#成員]
*/
public boolean download(String remote, String dir, String fileName)
throws IOException
{
File file = new File(dir + File.separator + fileName);
// 本地存在文件
if (file.exists())
{
if (logger.isDebugEnabled())
{
logger.debug("File is existsed.");
}
// 如果文件存在,但還未從FTP服務器上完全取下來,則需要等待
Long initialSize = 0L;
int i = 0;
while (initialSize != file.length())
{
i++;
initialSize = file.length();
try
{
Thread.sleep(100L);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
if (i > 1)
{
// 如果是剛下完的文件,則不需要再比對大小是否一致
return true;
}
}
Long localSize = file.length();
File localDir = new File(dir);
if (!localDir.exists())
{
localDir.mkdirs();
}
// 檢查遠程文件是否存在
if (remote.startsWith("/"))
{
remote = remote.substring(1);
}
if (ftpClient.listNames(remote).length <= 0)
{
// 文件不存在
logger.error("Could not find file from ftp server: " + remote);
return false;
}
// 計算遠程文件大小
String s = "SIZE " + remote + "\r\n";
ftpClient.sendCommand(s);
String s1 = ftpClient.getReplyString();
Long remoteSize = Long.parseLong(s1.substring(3).trim());
if (logger.isDebugEnabled())
{
logger.debug("localsize: " + localSize + ", remoteSize: " + remoteSize);
}
if (remoteSize.equals(localSize))
{
if (logger.isDebugEnabled())
{
logger.debug("File's size not changed.");
}
return true;
}
else if (localSize != 0L)
{
if (logger.isDebugEnabled())
{
logger.debug("File's size changed which needed re-download.");
}
//遠程文件和本地文件大小不一致,則刪除本地文件
file.delete();
//如果是EPUB書路徑,則需要把解壓過的臨時文件也一併刪除
if (dir.indexOf(EPUB_DIR) > 0)
{
deleteAll(localDir);
}
}
// 重連以回到根目錄
reconnect();
OutputStream out = new FileOutputStream(file);
InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes("UTF-8"),
ServerConfig.get("ftp/ftp-charset", "GBK")));
if (logger.isDebugEnabled())
{
logger.debug("Begin to downloaded file from ftp.");
}
byte[] bytes = new byte[1024];
int count;
while ((count = in.read(bytes)) != -1)
{
out.write(bytes, 0, count);
}
if (logger.isDebugEnabled())
{
logger.debug("File has been downloaded from ftp successfully.");
}
in.close();
out.close();
boolean upNewStatus = ftpClient.completePendingCommand();
if (upNewStatus)
{
return true;
}
else
{
return false;
}
}
//遞歸刪除文件夾
private void deleteAll(File file)
{
if (file.isDirectory() && !ArrayUtils.isEmpty(file.list()))
{
for (File childFile : file.listFiles())
{
deleteAll(childFile);
}
}
else
{
file.delete();
}
}
/** *//**
* 斷開與遠程服務器的連接
* @throws IOException
*/
public void disconnect() throws IOException{
if(ftpClient.isConnected()){
ftpClient.disconnect();
}
}
public static void main(String[] args) {
FtpUtils myFtp = new FtpUtils();
try {
myFtp.connect();
System.out.println(myFtp.download("/央視走西口/新浪網/走西口24.mp4", "E:\\走西口242.mp4", "123"));
myFtp.disconnect();
} catch (IOException e) {
System.out.println("連接FTP出錯:"+e.getMessage());
}
}
//使用: 下載文件
FtpUtils ftpUtils = new FtpUtils();
ftpUtils.connect();
ftpUtils.download(fileUrl, directoryPath, filename);
ftpUtils.disconnect();
}
案例四
sun.net.ftp.FtpClient.,該類庫主要提供了用於建立FTP連接的類。利用這些類的方法,編程人員可以遠程登錄到FTP服務器,列舉該服務器上的目錄,設置傳輸協議,以及傳送文件。FtpClient類涵蓋了幾乎所有FTP的功能,FtpClient的實例變量保存了有關建立”代理”的各種信息。下面給出了這些實例變量。
直接給大家上代碼,想要用功能的直接拿過來用接可以:
- import java.io.BufferedInputStream;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.sql.Connection;
- import java.sql.Statement;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Vector;
- import org.apache.commons.net.ftp.FTPClient;
- import org.apache.commons.net.ftp.FTPFile;
- import org.apache.commons.net.ftp.FTPReply;
- public class TfpTools {
- //連接ftp
- private FTPClient ftpClient = null;
- // public static String ip = “117.21.208.37”;
- // public static int port = 21;
- // public static String username = “eftp”;
- // public static String password = “e1f2t3p4”;
- // public static String sub_path = ”/opt/tomcat/webapps/photocdn/msgdata/”;
- /**
- * 連接ftp
- */
- public void connectServer(String ip,int port,String username,String password,String sub_path) throws Exception {
- int i = 10;
- if (ftpClient == null) {
- int reply;
- while (i > 0) {
- try {
- ftpClient = new FTPClient();
- if (port != 21)
- ftpClient.connect(ip, port);
- else
- ftpClient.connect(ip);
- ftpClient.login(username, password);
- reply = ftpClient.getReplyCode();
- if (!FTPReply.isPositiveCompletion(reply)) {
- ftpClient.disconnect();
- }
- System.out.println(”sub_path==============”+sub_path);
- // 對目錄進行轉換
- if (ftpClient.changeWorkingDirectory(sub_path)) {
- } else {
- ftpClient.disconnect();
- ftpClient = null;
- }
- } catch (Exception e) {
- e.printStackTrace();
- if (0 < i–) {
- try {
- Thread.sleep(10000);
- continue;
- } catch (Exception ex) {
- }
- }
- }
- i = 0;
- }
- }
- }
- /**
- * 文件上傳
- * @param ip
- * @param port
- * @param username
- * @param password
- * @param sub_path 遠程文件上傳目錄
- * @param localFilePath 本地文件存放路徑、、
- * @param newFileName 遠程生成的文件路徑和文件名
- * @throws Exception
- */
- public void uploadFile(String ip,int port,String username,String password,String sub_path,String localFilePath, String newFileName)throws Exception {
- BufferedInputStream buffIn = null;
- try {
- connectServer(ip,port,username,password,sub_path); //連接服務器
- System.out.println(”start upload”);
- buffIn = new BufferedInputStream(new FileInputStream(localFilePath));
- System.out.println(”find localFilePath success”);
- ftpClient.storeFile(newFileName, buffIn);
- System.out.println(”upload success”);
- } catch (Exception e) {
- e.printStackTrace();
- throw e;
- } finally {
- try {
- if (buffIn != null)
- buffIn.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- /**
- *
- * Definition: 讀取txt文件,存放到list中,以便於讀取
- * author: xiehaoyu
- * Created date: 2013-6-14
- * @param readTxt
- * @return
- */
- public static List<String> readTxt(String readTxt){
- BufferedReader br = null;
- List<String> list = new ArrayList<String>();
- try {
- br = new BufferedReader(new InputStreamReader(new FileInputStream(
- new File(readTxt))));
- String temp = br.readLine();
- while (temp != null) {
- String[] str=temp.toString().trim().split(”\\|”);
- for(String s : str){
- if(!“”.equals(s))
- list.add(s);
- }
- temp=br.readLine();
- }
- br.close();
- } catch (Exception e1) {
- e1.printStackTrace();
- }
- return list;
- }
- public void copyFile(String oldPath, String newPath) {
- try {
- int bytesum = 0;
- int byteread = 0;
- File oldfile = new File(oldPath);
- if (oldfile.exists()) { //文件存在時
- InputStream inStream = new FileInputStream(oldPath); //讀入原文件
- FileOutputStream fs = new FileOutputStream(newPath);
- byte[] buffer = new byte[1444];
- while ( (byteread = inStream.read(buffer)) != -1) {
- bytesum += byteread; //字節數 文件大小
- System.out.println(bytesum);
- fs.write(buffer, 0, byteread);
- }
- inStream.close();
- }
- }
- catch (Exception e) {
- System.out.println(”複製單個文件操作出錯”);
- e.printStackTrace();
- }
- }
- public void delFile(String filePathAndName) {
- try {
- String filePath = filePathAndName;
- filePath = filePath.toString();
- java.io.File myDelFile = new java.io.File(filePath);
- myDelFile.delete();
- }
- catch (Exception e) {
- System.out.println(”刪除文件操作出錯”);
- e.printStackTrace();
- }
- }
- /**
- * 文件下載。。
- * @param url ftp ip
- * @param port ftp端口
- * @param username
- * @param password
- * @param remotePath 下載路徑
- * @param fileName 下載文件中包含什麼文件名
- * @param localPath 本地存放路徑
- * @return
- */
- public static boolean downFile(
- String url,
- int port,
- String username,
- String password,
- String remotePath,
- String fileName,
- String localPath){
- boolean success = false;
- FTPClient ftp = new FTPClient();
- try {
- int reply;
- ftp.connect(url, port);
- //如果採用默認端口,可以使用ftp.connect(url)的方式直接連接FTP服務器
- ftp.login(username, password);//登錄
- reply = ftp.getReplyCode();
- if (!FTPReply.isPositiveCompletion(reply)) {
- ftp.disconnect();
- return success;
- }
- ftp.changeWorkingDirectory(remotePath);//轉移到FTP服務器目錄
- FTPFile[] fs = ftp.listFiles();
- TfpTools fu=new TfpTools();
- for(FTPFile ff:fs){
- if(ff.getName().contains(fileName)){
- if(fu.ToDetermineWhetherAFileExists(ff.getName())){
- File localFile = new File(localPath+“/”+ff.getName());
- OutputStream is = new FileOutputStream(localFile);
- ftp.retrieveFile(ff.getName(), is);
- is.close();
- }
- }
- }
- ftp.logout();
- success = true;
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (ftp.isConnected()) {
- try {
- ftp.disconnect();
- } catch (IOException ioe) {
- }
- }
- }
- return success;
- }
- public boolean ToDetermineWhetherAFileExists(String fileName){
- boolean flag=true;
- Vector<String> v=new Vector<String>();
- v=GetTestXlsFileName(”c:/JX_jiekou/src/backups”);
- for(int i=0;i<v.size();i++){
- String str=(String)v.elementAt(i);
- if(str.equals(fileName)){
- flag=false;
- }
- }
- return flag;
- }
- /**
- * 讀取本地某個目錄下,所有txt文件的文件名
- * @param fileAbsolutePath 本地文件目錄。
- * @return
- */
- public static Vector<String> GetTestXlsFileName(String fileAbsolutePath) {
- Vector<String> vecFile = new Vector<String>();
- File file = new File(fileAbsolutePath);
- File[] subFile = file.listFiles();
- for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
- // 判斷是否爲文件夾
- if (!subFile[iFileLength].isDirectory()) {
- String fileName = subFile[iFileLength].getName();
- // 判斷是否爲.txt結尾
- if (fileName.trim().toLowerCase().endsWith(“.txt”)) {
- vecFile.add(fileName);
- }
- }
- }
- return vecFile;
- }
- public boolean truncateTable(String tableName){
- Connection conn=null;
- Statement sm=null;
- String sql=”truncate table ”+tableName;
- try {
- conn=DBConfig.getConn(JkConfig.getDb_url(),JkConfig.getDb_username(),JkConfig.getDb_password(),0);
- sm=conn.createStatement();
- sm.executeUpdate(sql);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return true;
- }
- public void closeConnect() {
- try {
- if (ftpClient != null) {
- ftpClient.logout();
- ftpClient.disconnect();
- ftpClient=null;
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class TfpTools {
//連接ftp
private FTPClient ftpClient = null;
// public static String ip = "117.21.208.37";
// public static int port = 21;
// public static String username = "eftp";
// public static String password = "e1f2t3p4";
// public static String sub_path = "/opt/tomcat/webapps/photocdn/msgdata/";
/**
* 連接ftp
*/
public void connectServer(String ip,int port,String username,String password,String sub_path) throws Exception {
int i = 10;
if (ftpClient == null) {
int reply;
while (i > 0) {
try {
ftpClient = new FTPClient();
if (port != 21)
ftpClient.connect(ip, port);
else
ftpClient.connect(ip);
ftpClient.login(username, password);
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
}
System.out.println("sub_path=============="+sub_path);
// 對目錄進行轉換
if (ftpClient.changeWorkingDirectory(sub_path)) {
} else {
ftpClient.disconnect();
ftpClient = null;
}
} catch (Exception e) {
e.printStackTrace();
if (0 < i--) {
try {
Thread.sleep(10000);
continue;
} catch (Exception ex) {
}
}
}
i = 0;
}
}
}
/**
* 文件上傳
* @param ip
* @param port
* @param username
* @param password
* @param sub_path 遠程文件上傳目錄
* @param localFilePath 本地文件存放路徑、、
* @param newFileName 遠程生成的文件路徑和文件名
* @throws Exception
*/
public void uploadFile(String ip,int port,String username,String password,String sub_path,String localFilePath, String newFileName)throws Exception {
BufferedInputStream buffIn = null;
try {
connectServer(ip,port,username,password,sub_path); //連接服務器
System.out.println("start upload");
buffIn = new BufferedInputStream(new FileInputStream(localFilePath));
System.out.println("find localFilePath success");
ftpClient.storeFile(newFileName, buffIn);
System.out.println("upload success");
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
try {
if (buffIn != null)
buffIn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
*
* Definition: 讀取txt文件,存放到list中,以便於讀取
* author: xiehaoyu
* Created date: 2013-6-14
* @param readTxt
* @return
*/
public static List<String> readTxt(String readTxt){
BufferedReader br = null;
List<String> list = new ArrayList<String>();
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(
new File(readTxt))));
String temp = br.readLine();
while (temp != null) {
String[] str=temp.toString().trim().split("\\|");
for(String s : str){
if(!"".equals(s))
list.add(s);
}
temp=br.readLine();
}
br.close();
} catch (Exception e1) {
e1.printStackTrace();
}
return list;
}
public void copyFile(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { //文件存在時
InputStream inStream = new FileInputStream(oldPath); //讀入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字節數 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
}
catch (Exception e) {
System.out.println("複製單個文件操作出錯");
e.printStackTrace();
}
}
public void delFile(String filePathAndName) {
try {
String filePath = filePathAndName;
filePath = filePath.toString();
java.io.File myDelFile = new java.io.File(filePath);
myDelFile.delete();
}
catch (Exception e) {
System.out.println("刪除文件操作出錯");
e.printStackTrace();
}
}
/**
* 文件下載。。
* @param url ftp ip
* @param port ftp端口
* @param username
* @param password
* @param remotePath 下載路徑
* @param fileName 下載文件中包含什麼文件名
* @param localPath 本地存放路徑
* @return
*/
public static boolean downFile(
String url,
int port,
String username,
String password,
String remotePath,
String fileName,
String localPath){
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(url, port);
//如果採用默認端口,可以使用ftp.connect(url)的方式直接連接FTP服務器
ftp.login(username, password);//登錄
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(remotePath);//轉移到FTP服務器目錄
FTPFile[] fs = ftp.listFiles();
TfpTools fu=new TfpTools();
for(FTPFile ff:fs){
if(ff.getName().contains(fileName)){
if(fu.ToDetermineWhetherAFileExists(ff.getName())){
File localFile = new File(localPath+"/"+ff.getName());
OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
is.close();
}
}
}
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
public boolean ToDetermineWhetherAFileExists(String fileName){
boolean flag=true;
Vector<String> v=new Vector<String>();
v=GetTestXlsFileName("c:/JX_jiekou/src/backups");
for(int i=0;i<v.size();i++){
String str=(String)v.elementAt(i);
if(str.equals(fileName)){
flag=false;
}
}
return flag;
}
/**
* 讀取本地某個目錄下,所有txt文件的文件名
* @param fileAbsolutePath 本地文件目錄。
* @return
*/
public static Vector<String> GetTestXlsFileName(String fileAbsolutePath) {
Vector<String> vecFile = new Vector<String>();
File file = new File(fileAbsolutePath);
File[] subFile = file.listFiles();
for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
// 判斷是否爲文件夾
if (!subFile[iFileLength].isDirectory()) {
String fileName = subFile[iFileLength].getName();
// 判斷是否爲.txt結尾
if (fileName.trim().toLowerCase().endsWith(".txt")) {
vecFile.add(fileName);
}
}
}
return vecFile;
}
public boolean truncateTable(String tableName){
Connection conn=null;
Statement sm=null;
String sql="truncate table "+tableName;
try {
conn=DBConfig.getConn(JkConfig.getDb_url(),JkConfig.getDb_username(),JkConfig.getDb_password(),0);
sm=conn.createStatement();
sm.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
public void closeConnect() {
try {
if (ftpClient != null) {
ftpClient.logout();
ftpClient.disconnect();
ftpClient=null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
<div id="digg" articleid="24458469">
<dl id="btnDigg" class="digg digg_disable" onclick="btndigga();">
<dt>頂</dt>
<dd>0</dd>
</dl>
<dl id="btnBury" class="digg digg_disable" onclick="btnburya();">
<dt>踩</dt>
<dd>0</dd>
</dl>
</div>
<div class="tracking-ad" data-mod="popu_222"><a href="javascript:void(0);" target="_blank"> </a> </div>
<div class="tracking-ad" data-mod="popu_223"> <a href="javascript:void(0);" target="_blank"> </a></div>
<script type="text/javascript">
function btndigga() {
$(".tracking-ad[data-mod='popu_222'] a").click();
}
function btnburya() {
$(".tracking-ad[data-mod='popu_223'] a").click();
}
</script>
<div style="clear:both; height:10px;"></div>
<div class="similar_article">
<h4></h4>
<div class="similar_c" style="margin:20px 0px 0px 0px">
<div class="similar_c_t">
相關文章推薦
</div>
<div class="similar_wrap tracking-ad" data-mod="popu_36">
<ul class="similar_list fl">
</ul>
<ul class="similar_list fr">
</ul>
</div>
</div>
</div>