天天看點

FTP上傳和下載下傳檔案

使用FTP之前最好先在伺服器上安裝一個serv-u軟體,用它設定ftp服務表叫友善。

實作ftp檔案下載下傳

package cn.java.store.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FtpApche {
	private static FTPClient ftpClient = new FTPClient();
	private static String encoding = System.getProperty("file.encoding");
	/**
	 * Description: 從FTP伺服器下載下傳檔案
	 * 
	 * @Version1.0
	 * 
	 * @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 result = false;
		try {
			int reply;
			ftpClient.setControlEncoding(encoding);
			/*
			 * 為了上傳和下載下傳中文檔案,有些地方建議使用以下兩句代替 new
			 * String(remotePath.getBytes(encoding),"iso-8859-1")轉碼。 經過測試,通不過。
			 */
			// FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
			// conf.setServerLanguageCode("zh");
			ftpClient.connect(url, port);
			// 如果采用預設端口,可以使用ftp.connect(url)的方式直接連接配接FTP伺服器
			ftpClient.login(username, password);// 登入
			// 設定檔案傳輸類型為二進制
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			// 擷取ftp登入應答代碼
			reply = ftpClient.getReplyCode();
			// 驗證是否登陸成功
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
				System.err.println("FTP server refused connection.");
				return result;
			}
			// 轉移到FTP伺服器目錄至指定的目錄下
			ftpClient.changeWorkingDirectory(new String(remotePath.getBytes(encoding), "iso-8859-1"));
			// 擷取檔案清單
			FTPFile[] fs = ftpClient.listFiles();
			for (FTPFile ff : fs) {
				if (ff.getName().equals(fileName)) {
					File localFile = new File(localPath + "/" + ff.getName());
					OutputStream is = new FileOutputStream(localFile);
					ftpClient.retrieveFile(ff.getName(), is);
					is.close();
				}
			}
			ftpClient.logout();
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return result;
	}

	/**
	 * 将FTP伺服器上檔案下載下傳到本地
	 * 
	 */
	public void testDownFile() {
		try {
			boolean flag = downFile("10.0.0.102", 21, "admin", "123456", "/", "ip.txt", "E:/");
			System.out.println(flag);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		FtpApche fa = new FtpApche();
		fa.testDownFile();
	}
}
           

單個檔案下載下傳

//單個檔案下載下傳
 public void Ftpdownload(String reaName,String fileName,String remote,HttpServletResponse response,HttpServletRequest request) throws IOException 
      { 
          // 開啟輸出流彈出檔案儲存路徑選擇視窗 
        response.setContentType("application/octet-stream"); 
        response.setContentType("application/OCTET-STREAM;charset=UTF-8"); 
        //解決下載下傳檔案中文名稱亂碼的問題 
        String agent = request.getHeader("USER-AGENT");  
      if(agent != null && agent.toLowerCase().indexOf("firefox") > 0)
      {
          reaName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(reaName.getBytes("UTF-8")))) + "?=";    
      }
      else
      {
          reaName =  java.net.URLEncoder.encode(reaName, "UTF-8");
      }
        response.setHeader("Content-Disposition", "attachment;filename=" +reaName); 
        OutputStream out = response.getOutputStream(); 
        // 轉移到FTP伺服器目錄至指定的目錄下
        ftpClient.changeWorkingDirectory(new String(remote.getBytes(LOCAL_CHARSET), SERVER_CHARSET));
        //下載下傳FTP伺服器指定檔案
        ftpClient.retrieveFile(new String(fileName.getBytes(LOCAL_CHARSET), SERVER_CHARSET), out);
        out.close(); 
      } 
           

所有檔案打包下載下傳

//打包下載下傳
 public void download(Map<String,String> map,String isbn,HttpServletResponse response){ 
          // 開啟輸出流彈出檔案儲存路徑選擇視窗 
        response.setContentType("application/octet-stream"); 
        response.setContentType("application/OCTET-STREAM;charset=UTF-8"); 
         //解決下載下傳檔案中文名稱亂碼的問題 
        try {
             SimpleDateFormat simpleDateFormat;  
             simpleDateFormat = new SimpleDateFormat("yyyyMMdd");  
             Date date = new Date();  
            String folderName=isbn+"-"+simpleDateFormat.format(date);
            response.setHeader("Content-Disposition", "attachment;filename=" +URLEncoder.encode(folderName+".zip", "UTF-8"));
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } 
        //設定緩存大小
        byte[] buffer = new byte[1024];  
        OutputStream out;
        try {
            out = response.getOutputStream();
            //開啟壓縮流
            ZipOutputStream zipout = new ZipOutputStream(out);
            int len; 
            FTPFile[] listFiles=ftpClient.listFiles();
            Set<String> set = map.keySet();  
            List<InputStream> list = new ArrayList<InputStream>();
            for (String key : set) {  
                // 轉移到FTP伺服器目錄至指定的目錄下
                ftpClient.changeWorkingDirectory(new String(map.get(key)
                        .getBytes(LOCAL_CHARSET), SERVER_CHARSET));


                String string = new String(key.getBytes(LOCAL_CHARSET),SERVER_CHARSET);
                //從FTP伺服器下載下傳檔案到檔案流
                InputStream retrieveFileStream = ftpClient
                        .retrieveFileStream(string);
                //标記為壓縮包中内的一個新檔案
                zipout.putNextEntry(new ZipEntry(key)); 
                //寫入輸出流
                while ((len = retrieveFileStream.read(buffer)) > 0) {    
                    zipout.write(buffer, 0, len);    
                }
                //關閉下載下傳流
                retrieveFileStream.close(); 
                //FTP内置方法,必須調用才能下載下傳下一個檔案流
                ftpClient.completePendingCommand();
            } 
            //關閉壓縮流
            zipout.close();  
        } catch (IOException e) {
            // TODO Auto-generated catch block 
            e.printStackTrace();
        } 
      } 
           

FTP的檔案上傳

import java.io.File;
import java.io.FileInputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FTPTest_05 {
private FTPClient ftp;
/** 
* 
* @param path 上傳到ftp伺服器哪個路徑下 
* @param addr 位址 
* @param port 端口号 
* @param username 使用者名 
* @param password 密碼 
* @return 
* @throws Exception 
*/
private boolean connect(String path,String addr,int port,String username,String password) throws Exception {
boolean result = false;
ftp = new FTPClient();
int reply;
ftp.connect(addr,port);
ftp.login(username,password);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
ftp.changeWorkingDirectory(path);
result = true;
return result;
}
/** 
* 
* @param file 上傳的檔案或檔案夾 
* @throws Exception 
*/
private void upload(File file) throws Exception{
if(file.isDirectory()){
ftp.makeDirectory(file.getName());
ftp.changeWorkingDirectory(file.getName());
String[] files = file.list();
for (int i = 0;i < files.length;i++) {
File file1 = new File(file.getPath()+"\\"+files[i] );
if(file1.isDirectory()){
upload(file1);
ftp.changeToParentDirectory();
}else{
File file2 = new File(file.getPath()+"\\"+files[i]);
FileInputStream input = new FileInputStream(file2);
ftp.storeFile(file2.getName(), input);
input.close();
}
}
}else{
File file2 = new File(file.getPath());
FileInputStream input = new FileInputStream(file2);
ftp.storeFile(file2.getName(), input);
input.close();
}
}
public static void main(String[] args) throws Exception{
FTPTest_05 t = new FTPTest_05();
boolean connFlag = t.connect("/", "10.0.0.105", 21, "ls", "123456");
System.out.println("connFlag : " + connFlag);
File file = new File("D:\\test02");//本機被傳檔案的位址
System.out.println("file : " + file);
t.upload(file);
System.out.println("upload : " + "ok");
}
}