ftp文件上傳3

近日我正在做FTP上傳的程序;
我說了一下我開發的環境;
1。我們程序開發是在windows下;
2。程序的運行環境是在linux下的,就是weblogic在linux
3。FTP的服務器是在windows下的;
4。客戶端也是在windows下的;

我想這個環境應該是大多的環境配置,也就不多講了;

在開發FTP上傳程序的時候主要遇到的問題如下:

1。上傳組件的選擇
現在FTP的上傳組件很多;
(1)JDK裏自帶的就有一套; sun.net.ftp.*目錄下,這個實現的功能簡單,而且沒有說明文檔,所以不推薦
(2)還有是edtftp,這個組件有相關的文檔說明及較強的現實功能,但是沒有解決文件名亂碼的問題,可能是我自己設置的問題,
如果有人解決了,在這裏請教一下是如何實現的;
(3)這次我用的就是Apache 的CommonNet包下的FTP,這個組件是開源的可以看到源代碼及完整的說明文檔。功能較強大;很簡單的就
解決了我中文文件名亂碼的問題

2。上傳時中文文件名亂碼
我的環境以經交代過了;中文文件名亂碼就是因爲環境所引起的
(客戶端)windows[GBK]------>(服務器)linux[UFT-8]------>(FTP服務器)windows[GBK]
這樣一來文件名在傳輸的過程中發生亂碼

3。下載時文件下載到一半,就是沒有下載完整
文件下載一部分沒沒有下載完整;如果圖片文件,下載後打開只能看到部份。未能下載完整
這個原因是在下載過程中,文件沒有下載完整,FTP連接就以經關閉所以造成文件下載部分的結果
所以我項目中FTP的程序,從新寫了一次,做成了工具類;
大家如果發生類似的問題,希望可以幫助到[我也是看了網上很多朋友的例子,在這裏感謝一下,所謂“飲水思源”啊]

如果轉載,請原文轉載

作者: 龔成偉(elwin)
廁所裏冥想
http://dxadnwfn.cublog.cn/
package com.skyon.mica.system.common;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
/**
* 文件FTP上傳基類
*
* @author : 龔成偉(Elwin)
* @createDate: Dec 26, 2007-4:57:47 PM
* @version $Revision: 1.1 $
*
*/
public class ApacheCommonNettoFtpBase {
private static String ip;
private static String user;
private static String password;
private static int port;
private static FTPClient ftpClient;

/**
  * 初始化
  * @param ip FTP服務器地址
  * @param user 服務名
  * @param password 密碼
  * @param port 端口號
  */
public ApacheCommonNettoFtpBase(String ip,String user,String password,int port){
  this.ip=ip;
  this.user=user;
  this.password=password;
  this.port=port;
}

/**
  * 上傳文件
  * @param file 文件
  * @return
  */
public boolean uploadFile(File file){
  if (!file.isFile()) {
   //不是文件
   return false;
  }else if(!fileSize(file)){
   //控制文件大小
   return false;
  }
  
  //
  if (!connectServer()) {
   return false;
  }
  
  //給文件加上時間撮,防止服務器文件重複
  String fileName=file.getName();
  int lastIndex=fileName.lastIndexOf(".");
  fileName=fileName.substring(0,lastIndex)+"_"+System.currentTimeMillis()+fileName.substring(lastIndex);
  
  try {
   FileInputStream fis=new FileInputStream(file);
   if(!ftpClient.storeFile(gbktoiso8859(fileName), fis)){
    closeConnect();
    return false;
   }
  } catch (IOException e) {
   e.printStackTrace();
   return false;
  }finally{
   closeConnect();
  }
  
  return true;
}

/**
  * 上傳文件
  * @param file 文件
  * @param path 上傳服務器路徑
  * @return
  */
public boolean uploadFile(File file,String path){
  //轉到path路徑
  path=this.pathAddress(path);
  //創建路徑
  mkdir(path);
  //進入服務器目錄
  if (!this.changeWorkingDirectory(path)) {
   return false;
  }
  
  return uploadFile(file);
}

/**
  * 下載文件
  * @param filename 文件名
  * @return
  */
public InputStream downloadFile(String filename){
  if (!connectServer()) {
   return null;
  }
  InputStream is=null;
  try {
   is=ftpClient.retrieveFileStream(gbktoiso8859(filename));
   return is;
  } catch (IOException e) {
   e.printStackTrace();
   closeConnect();
   return null;
  }
  //退出FTP服務器
  //不能馬上退出,不然會出現文件下載到一半,沒有下載完整的情況
  //this.closeConnect();
}

/**
  * 下載文件
  * @param filename 文件名
  * @param path 路徑
  * @return
  */
public InputStream downloadFile(String filename,String path){
  //轉到path路徑
  path=this.pathAddress(path);
  if (!this.changeWorkingDirectory(path)) {
   return null;
  }
  
  return downloadFile(filename);
}
/**
  * 刪除文件
  * @param path  路徑
  * @param filename 文件名
  * @return
  */
public boolean deleteFile(String filename,String path){
  
  //轉到path路徑
  path=this.pathAddress(path);
  if (!this.changeWorkingDirectory(path)) {
   return false;
  }
  //刪除文件
  return deleteFile(filename);
}
/**
  * 刪除文件
  *
  * @param filename 文件名
  * @return
  */
public boolean deleteFile(String filename) {
  try {
   if (!connectServer()) {
    return false;
   }
   return ftpClient.deleteFile(gbktoiso8859(filename));
  } catch (IOException ioe) {
   ioe.printStackTrace();
   closeConnect();
   return false;
  }
}

/**
  * 文件列表 顯示path目錄下載文件夾和文件
  * @param path
  */
public void fileList(String path){
  try {
   path=pathAddress(path);
   if (connectServer()) {
    FTPFile[] vFiles = ftpClient.listFiles(gbktoiso8859(path));
             for (int i = 0; i
   }
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   // 退出FTP服務器
   this.closeConnect();
  }
  
}

/**
  * 創建路徑
  * @param path 路徑名稱
  * @return
  */
public boolean mkdir(String path){
  if (!connectServer()) {
   return false;
  }
  try{
   path=this.pathAddress(path);
   return ftpClient.makeDirectory(gbktoiso8859(path));
  }catch(IOException e){
   e.printStackTrace();
   return false;
  }
}
/**
  * 重命名文件
  * @param oldFileName --原文件名
  * @param newFileName --新文件名
  */
public  boolean  renameFile(String oldFileName, String newFileName) {
  try {
   if (!connectServer()) {
    return false;
   }
   return ftpClient.rename(gbktoiso8859(oldFileName), gbktoiso8859(newFileName));
  } catch (IOException ioe) {
   ioe.printStackTrace();
   closeConnect();
   return false;
  }
}
/**
  * 進入到服務器的某個目錄下
  * @param directory
  */
public  boolean changeWorkingDirectory(String directory) {
  try {
   if (!connectServer()) {
    return false;
   }
   return ftpClient.changeWorkingDirectory(gbktoiso8859(directory));
  } catch (IOException ioe) {
   ioe.printStackTrace();
   return false;
  }
}
/**
  * 返回到上一層目錄
  */
public  boolean changeToParentDirectory() {
  try {
   if (!connectServer()) {
    return false;
   }
   return ftpClient.changeToParentDirectory();
  } catch (IOException ioe) {
   ioe.printStackTrace();
   closeConnect();
   return false;
  }
}
/**
  * 登錄ftp服務器
  *
  */
public boolean connectServer() {
  
  if (ftpClient==null) {
   try {
    ftpClient=new FTPClient();
    //所有使用iso-8859-1做爲通訊編碼集
    //ftpClient.setControlEncoding("iso-8859-1");
    //ftpClient.configure(getFTPClientConfig());
   
    ftpClient.connect(ip,port);
   
    if (!ftpClient.login(user, password)) {
     //登錄失敗
     return false;
    }
    //狀態
    int reply = ftpClient.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
     closeConnect();
     return false;
    }
   
    //  用被動模式傳輸
    ftpClient.enterLocalPassiveMode();
    // 將文件傳輸類型設置爲二進制
    ftpClient.setFileType(
FTP.BINARY_FILE_TYPE
);
    //防止server超時斷開
    //ftpClient.setDefaultTimeout(60000);
    //10連接超時
    ftpClient.setSoTimeout(10000);
   }catch(SocketException se){
    se.printStackTrace();
    return false;
   } catch (Exception e) {
    e.printStackTrace();
    return false;
   }
  }
  return true;
}

/**
  * 關閉連接
  */
private  void closeConnect() {
  try {
   if (ftpClient != null) {
    ftpClient.logout();
    ftpClient.disconnect();
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
}
/**
  * 寫文件到本地
  * @param is 文件流
  * @param allPath 全路徑=文件路徑+文件名
  * @return
  */
public boolean writeFile(InputStream is,String allPath){
  if (is==null || allPath==null) {
   return false;
  }
  try {
   //默認也是2048
   int buffered=2048;
   BufferedInputStream bis=new BufferedInputStream(is,buffered);
   BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(allPath));
   final byte[] bytes = new byte[2048];
   int c;
   while ((c = bis.read(bytes)) != -1) {
    bos.write(bytes);
   }
      //將緩衝區中的數據全部寫出
   bos.flush();
   //關閉流
   bis.close();
   bos.close();
   return true;
  } catch (Exception e) {
   e.printStackTrace();
   return false;
  }
}
/**
  * 寫文件到本地
  * @param is 文件流
  * @param path 文件路徑
  * @param filename 文件名
  * @return
  */
public boolean writeFile(InputStream is,String path,String filename){
  path=pathAddress(path);
  return writeFile(is, path+filename);
}
/**
  * 寫文件到本地
  * @param file 文件
  * @param path 寫到的路徑
  * @return
  */
public boolean writeFile(File file,String path){
  if (!file.isFile()) {
   return false;
  }
  try {
   FileInputStream is=new FileInputStream(file);
   path=pathAddress(path);
   this.writeFile(is, path+file.getName());
  } catch (IOException e) {
   e.printStackTrace();
  }
  
  
  return true;
}
/**
  * 設置FTP客服端的配置--一般可以不設置
  * @return
  */
private static FTPClientConfig getFTPClientConfig() {
  FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
  conf.setServerLanguageCode("zh");
  
  return conf;
}

/**
  * 控制文件的大小,默認爲5M
  * @param file_in 文件
  */
private boolean fileSize(File file_in) {
  return this.fileSize(file_in,5);
}

/**
  * 控制文件的大小
  * @param file_in 文件
  * @param size 文件大小,單位爲M
  */
private boolean fileSize(File file_in,int size) {
  if (file_in == null || file_in.length() == 0) {
   //文件爲空
   return false;
  } else {
   if (file_in.length() > (1024 * 1024 * size)){
    //文件大小不能大與size
    return false;
   }
  }
  return true;
}
/**
  * 格式化文件路徑 檢查path最後有沒有分隔符'\'
  * @param path
  * @return
  */
public String pathAddress(String path){
  
  if (path==null || path.length()  GBK]
  *不同的平臺需要不同的轉碼
  * @param obj
  * @return
  */
private static String iso8859togbk(Object obj) {
  try {
   if (obj == null)
    return "";
   else
    return new String(obj.toString().getBytes("iso-8859-1"), "GBK");
  } catch (Exception e) {
   return "";
  }
}

/**
  * 轉碼[GBK ->  ISO-8859-1]
  *不同的平臺需要不同的轉碼
  * @param obj
  * @return
  */
private static String gbktoiso8859(Object obj) {
  try {
   if (obj == null)
    return "";
   else
    return new String(obj.toString().getBytes("GBK"), "iso-8859-1");
  } catch (Exception e) {
   return "";
  }
}

public static String getIp() {
  return ip;
}
public static void setIp(String ip) {
  ApacheCommonNettoFtpBase.ip = ip;
}
public static String getUser() {
  return user;
}
public static void setUser(String user) {
  ApacheCommonNettoFtpBase.user = user;
}
public static String getPassword() {
  return password;
}
public static void setPassword(String password) {
  ApacheCommonNettoFtpBase.password = password;
}
public static int getPort() {
  return port;
}
public static void setPort(int port) {
  ApacheCommonNettoFtpBase.port = port;
}

/**
  * 測試
  * @param args
  */
public static void main(String[] args) {
  String ip="155.222.30.137";
  String user="elwin";
  String password="elwin";
  int port=21;
  String path="f:";
  File file=new File("d:"+File.separator+"銀團社團貸款_1451877459518.doc");
  ApacheCommonNettoFtpBase ftp=new ApacheCommonNettoFtpBase(ip,user,password,port);
  //ftp.uploadFile(file,"創建目錄");
  //InputStream is=ftp.downloadFile("銀團社團貸款_1451877459518_1198723453937.doc","創建目錄");
  //ftp.writeFile(is, "F:", "銀團社團貸款.doc");
  //ftp.deleteFile("銀團社團貸款_1451877459518_1198658605453.doc","創建目錄");
  //ftp.ftpfileList(path);
  //ftp.fileList("");
  long l1=System.currentTimeMillis();
  
ftp.writeFile(file
, path);
  System.out.println(System.currentTimeMillis()-l1);
  
  try{
   long l2=System.currentTimeMillis();
   BufferedRandomAccessFile braf=new BufferedRandomAccessFile(file,"rw",10);
   File f=new File("F:"+File.separator+"sdfsdf.doc");
   f.createNewFile();
   
   BufferedRandomAccessFile b=new BufferedRandomAccessFile(f,"rw",10);
   final byte[] bytes = new byte[1024];
   int c;
   while ((c = braf.read(bytes)) != -1) {
    b.write(bytes,0,c);
   }
   System.out.println(System.currentTimeMillis()-l2);
  }catch(Exception e){
   e.printStackTrace();
  }
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章