iT邦幫忙

DAY 18
4

JSP 學習分享系列 第 18

JSP 和 apache的FTP Tool

當一個ftp 的客戶端上傳,下載和刪除檔案
需要下載jar檔
http://commons.apache.org/downloads/download\_net.cgi
上傳,下載和刪除檔案
=== ftpSample.jsp ===

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.io.File"%>
<%@ page import="java.io.FileInputStream"%>
<%@ page import="java.io.FileOutputStream"%>
<%@ page import="java.io.IOException"%>
<%@ page import="org.apache.commons.net.ftp.FTP"%>
<%@ page import="org.apache.commons.net.ftp.FTPClient"%>
<%@ page import="org.apache.commons.net.ftp.FTPFile"%>
<%@ page import="org.apache.commons.net.ftp.FTPReply"%>
<%
  String server = "10.10.8.7";
  String username = "xxxxxxxx";
  String password = "xxxxxxxx";
  String directory = "Res";
  String filename = "D:/kill/net.txt";
  File filePut = new File(filename);
  String filename2 = "D:/kill/net2.txt";
  File fileGet = new File(filename2);
  String filename3 = "net.txt";

  FTPClient ftp = new FTPClient();
  // We want to timeout if a response takes longer than 30 seconds
  ftp.setDefaultTimeout(30000);
  try {
    int reply;
    ftp.connect(server);
    System.out.println("Connected to " + server + ".");
    System.out.print(ftp.getReplyString());

    // After connection attempt, you should check the reply code to verify
    // success.
    reply = ftp.getReplyCode();

    if (!FTPReply.isPositiveCompletion(reply)) {
      ftp.disconnect();
      System.err.println("FTP server refused connection.");
      return;
    }
    // transfer files
    if (ftp.login(username, password)) {
      long totalSize = 0L;
      for (FTPFile file : ftp.listFiles(directory)) {
        System.out.printf("%s %s [%d bytes]\n",
        (file.isDirectory() ? "[D]" : "   "), file.getName(), file.getSize());
        if (!file.isDirectory()) {
          totalSize += file.getSize();
        }
      }
      System.out.println("totalSize = " + totalSize/(1024 * 1024) + "MB");

      // PASV
      ftp.enterLocalPassiveMode();
      // CWD
      ftp.changeWorkingDirectory(directory);
      // PWD
      System.out.println(ftp.printWorkingDirectory());
      // TYPE I
      ftp.setFileType(FTP.BINARY_FILE_TYPE);
      // PUT
      ftp.storeFile(filePut.getName(), new FileInputStream(filePut));
      // GET
      ftp.retrieveFile(filePut.getName(), new FileOutputStream(fileGet));
      // DELE
      ftp.deleteFile(filename3);
    }
    ftp.logout();
  } catch (Exception e) {
    System.out.println(e);
  } finally {
    if (ftp.isConnected()) {
      try {
        ftp.disconnect();
      } catch (Exception ex) {
        System.out.println(ex);
      }
    }
  }
%>

上一篇
JSP 和Apache Upload
下一篇
JSP 和Zip Tool
系列文
JSP 學習分享30

尚未有邦友留言

立即登入留言