Topic: 轻松玩转FTP,HTTP,POP3,SMTP,TELNET客户端JAVA程序 之FTP篇 |
Print this page |
1.轻松玩转FTP,HTTP,POP3,SMTP,TELNET客户端JAVA程序 之FTP篇 | Copy to clipboard |
Posted by: bfcatfriends Posted on: 2003-08-07 09:17 http://www.jscape.com/可以免费下载inetfactory开发包。 因为本人用过,感觉很好,向大家推荐使用。请多多指教。 下面给出关于FTP的PACKAGE使用说明: 1 Overview 1.1 Introduction The FTP (File Transfer Protocol) component provides an interface for transmitting data to/from an FTP server. The FTP component implements standards defined in RFC 959 and RFC 1579. 1.2 Target audience This document is intended to serve as a technical guide to using the FTP component. Users should understand the Java™ programming language and be proficient in writing Java™ applications. A basic understanding of FTP and networking protocols is also helpful. 1.3 General features Ability to upload / download binary and ASCII files Ability to automatically detect and set data transfer mode Ability to connect from behind a firewall using a passive FTP connection Ability to upload / download files using a regular expression Ability to monitor progress of upload / download using easy to implement event listeners Ability to upload / download directories recursively 2 Connecting to an FTP server 2.1 Establishing a connection To establish a connection to an FTP server, create an FTP instance and provide the required hostname, username and password. Example: Ftp ftp = new Ftp("ftp.myserver.com","jsmith","secret"); ftp.connect(); 2.2 Setting network connection timeout You can use the setTimeout method to define the maximum number of milli-seconds to wait when establishing a connection to an FTP server. Failure to establish a connection within the maximum time allowed will result in an FtpException. Example: ftp.setTimeout(5000); ftp.connect(); 2.3 Connecting from behind a firewall If you are connecting from behind a firewall you must set the FTP instance to use passive mode prior to establishing a connection. Example: ftp.setPassive(true); ftp.connect(); 3 Capturing FTP related events 3.1 Overview The FTP component may publish one or more events during the lifetime of an FTP session. Any object that subscribes to events published by the FTP component can receive and process these events. 3.2 Listening for events For an object to listen for events published by the FTP component the following three (3) steps are required. 1. Set object to implement FtpListener or extend FtpAdapter class. 2. Overload event handling methods. 3. Subscribe object to receive events published by FTP instance. The FtpListener class is a pure interface and can be used in cases where the class you defined to listen for events already extends another class type. The FtpAdapter class extends the FtpListener interface and can be used in cases where there is no need for class inheritance. Note: Unless your class requires inheritance it is generally easier to use the FtpAdapter class as it provides default implementations for all the event handler methods defined in the FtpListener interface. This allows you to overload only the event handler methods that you are interested in. Example 1: import com.jscape.inet.ftp.*; public class MyFtpListener implements FtpListener { public void commandSent(FtpCommandEvent evt) { // process event } public void connected(FtpConnectedEvent evt) { // process event } public void disconnected(FtpDisconnectedEvent evt) { // process event } public void download(FtpDownloadEvent evt) { // process event } public void listing(FtpListingEvent evt) { // process event } public void progress(FtpProgressEvent evt) { // process event } public void responseReceived(FtpResponseEvent evt) { // process event } public void upload(FtpUploadEvent evt) { // process event } public static void main(String[] args) { try { Ftp ftp = new Ftp("ftp.myserver.com","jsmith","secret"); // subscribe MyFtpListener to events published ftp.addFtpListener(new MyFtpListener()); ftp.connect(); ftp.disconnect(); } catch(Exception e) { e.printStackTrace(); } } } Example 2: import com.jscape.inet.ftp.*; public class MyFtpAdapter extends FtpAdapter { public void connected(FtpConnectedEvent evt) { // process event } public void disconnected(FtpDisconnectedEvent evt) { // process event } public static void main(String[] args) { try { Ftp ftp = new Ftp("ftp.myserver.com","jsmith","secret"); ftp.addFtpListener(new MyFtpAdapter()); ftp.connect(); ftp.disconnect(); } catch(Exception e) { e.printStackTrace(); } } } 3.3 FtpConnectedEvent The FtpConnectedEvent is published by the FTP instance once a connection to the FTP server has been established. See JavaDoc for details on this event. 3.4 FtpDisconnectedEvent The FtpDisconnectedEvent is published by the FTP instance once the connection to the FTP server has been released. See JavaDoc for details on this event. 10 3.5 FtpDownloadEvent The FtpDownloadEvent is published by the FTP instance for each file downloaded from the FTP server. See JavaDoc for details on this event. 3.6 FtpListingEvent The FtpListingEvent is published by the FTP instance for each directory listing retrieved from the FTP server. See JavaDoc for details on this event. 3.7 FtpProgressEvent The FtpProgressEvent is published by the FTP instance one or more times during the transfer of files to / from the FTP server. See JavaDoc for details on this event. 3.8 FtpCommandEvent The FtpCommandEvent is published by the FTP instance for each command sent to the FTP server. See JavaDoc for details on this event. 3.9 FtpResponseEvent The FtpResponseEvent is published by the FTP instance for each response received from the FTP server. See JavaDoc for details on this event. 4 Setting your directory 4.1 Setting your local directory Your local directory is the relative path from which all files will be uploaded from or downloaded to when communicating with an FTP server. If you do not define the local directory the local directory will default to the directory from which the Java™ VM was instantiated. ftp.setLocalDir (new File("/usr/home")); 4.2 Setting your remote directory Your remote directory is the directory on the FTP server from which all files will be uploaded to or downloaded from when communicating with the FTP server. If you do not define the remote directory then the remote directory will default to the directory provided upon successful login to the FTP server. ftp.setDir("home"); 5 Retrieving a directory listing 5.1 Retrieving a remote directory listing There are two ways that you can retrieve a directory listing from the FTP server. The method used will depend on the FTP server you are connecting to and how you want to process the results. If you want to simply print out the results of a directory listing you may use the getDirListingAsString method. This returns a String representing the response received by the FTP server upon requesting a directory listing. If you are wanting to process the results, evaluating each file returned in the directory listing then you can use the getDirListing method. This returns an Enumeration of FtpFile. Each instance of FtpFile contains information such as the filename, filesize, timestamp etc. Warning: The getDirListing method only works for FTP servers which return a directory listing in the standard UNIX or MS-DOS formats. For all other formats it is recommended that you use the getDirListingAsString method. Example 1: String results = ftp.getDirListingAsString(); System.out.println(results); Example 2: Enumeration files = ftp.getDirListing(); while(files.hasMoreElements()) { FtpFile file = (FtpFile) files.nextElement(); System.out.println(file.getFilename()); } 5.2 Retrieving a local directory listing You can retrieve an Enumeration of files from your current local directory. The current local directory can be set when creating a new FTP instance or by using the setLocalDir method. See Setting your local directory for details. Example: Enumeration files = ftp.getLocalDirListing(); while(files.hasMoreElements()) { File f = (File) files.nextElement(); System.our.println(f.getName()); } 6 Uploading files 6.1 Automatically detecting the transfer mode When uploading files the transfer mode is by default set to automatically detect whether to use ASCII or BINARY transfer mode based on the file extension of the file transferred. If you are uploading multiple files it is often convenient to have the transfer mode automatically detected and set based on the type of file being uploaded. Binary files such as images should be uploaded using the binary transfer mode. ASCII files such as text documents should be uploaded using the ASCII transfer mode. You can have this handled automatically using the setAuto method. Example: ftp.setAuto(true); ftp.upload("image.gif"); ftp.upload("file.txt"); 6.2 Uploading binary files To upload binary files you must change the transfer mode to binary. All files will be uploaded from your current local directory. See Setting your local directory for details. Example: ftp.setAuto(false); ftp.setBinary(); ftp.upload("image.gif"); 6.3 Uploading ASCII text files To upload ASCII text files you must change the transfer mode to ASCII. All files will be uploaded from your current local directory. See Setting your local directory for details. Note: The default transfer mode is ASCII text Example: ftp.setAuto(false); ftp.setAscii(); ftp.upload("file.txt"); 6.4 Uploading multiple files You can upload multiple files using the mupload method and a wildcard expression. All files will be uploaded from your current local directory. See Setting your local directory for details. Example: ftp.mupload("*.txt"); 6.5 Uploading a directory You can upload an entire directory using the uploadDir method and a File representing a directory on your local system. Example: File dir = new File("c:/testdir"); ftp.uploadDir(dir); 6.6 Appending files You can append data to a remote file using any of the Ftp#uploadFile methods that take a second boolean argument. Rather than replace the remote file, this will append the data that you are uploading to the remote file. Example: File file = new File("c:/tmp/test.txt"); // append file ftp.uploadFile(file,true); 7 Downloading files 7.1 Automatically detecting the transfer mode When downloading files the transfer mode is by default set to automatically detect whether to use ASCII or BINARY transfer mode based on the file extension of the file transferred. If you are downloading multiple files it is often convenient to have the transfer mode automatically detected. Binary files such as images should be downloaded using the BINARY transfer mode. ASCII files such as text documents should be downloaded using the ASCII transfer mode. You can have this handled automatically using the setAuto method. Example: ftp.setAuto(true); ftp.upload("image.gif"); ftp.upload("file.txt"); 7.1 Downloading binary files To download binary files you must change the transfer mode to binary. All files will be downloaded relative to your current remote directory. See Setting your remote directory for details. Example: ftp.setAuto(false); ftp.setBinary(); ftp.download("image.gif"); 7.2 Downloading text files To download ASCII text files you must change the transfer mode to ASCII. All files will be downloaded relative to your current remote directory. See Setting your remote directory for details. Note: The default transfer mode is ASCII text Example: ftp.setAuto(false); ftp.setAscii(); ftp.download("file.txt"); 7.3 Downloading multiple files You can download multiple files using the mdownload method along with a regular expression. All files will be downloaded relative to your current remote directory. See Setting your remote directory for details. Example: ftp.mdownload("*.txt"); 7.4 Downloading a directory You can download an entire directory using the downloadDir method and a directory name. Directory to download is relative to your current remote directory. See Setting your remote directory for details. Example: ftp.downloadDir("testdir"); 8 Remote file operations 8.1 Creating a remote directory You can create a remote directory on the FTP server using the makeDir method. The directory created is relative to your current remote directory. See Setting your remote directory for details. Example: ftp.makeDir("testdir"); 8.2 Creating a local directory You can create a local directory using the makeLocalDir method. The directory created is relative to your current local directory. See Setting your local directory for details. Example: ftp.makeLocalDir("testdir"); 8.3 Deleting a remote directory You can delete a remote directory on the FTP server using the deleteDir method. The directory deleted is relative to your current remote directory. See Setting your remote directory for details. Example: ftp.deleteDir("testdir"); 8.4 Renaming a file You can rename a file using the renameFile method providing the current file name and the new file name. Example: ftp.renameFile("file.txt","newfile.txt"); 8.5 Deleting a file You can delete a file using the deleteFile method. Example: ftp.deleteFile("file.txt"); 8.6 Retrieving filesize information You can retrieve the byte size of a file using the getFilesize method. Note: The getFilesize method utilizes a command that is supported by a majority of FTP servers however is not officially recognized by RFC 959. Example: long bytes = ftp.getFilesize("file.txt"); 8.7 Retrieving file timestamp information You can retrieve the date a file was last modified using the getFileTimestamp method. Note: The getFileTimestamp method utilizes a command that is supported by a majority of FTP servers however is not officially recognized by RFC 959. Example: Date d = ftp.getFileTimestamp("file.txt"); 9 Troubleshooting 9.1 PORT command failure When attempting to establish a connection to an FTP server you may receive the following error message. Example: 500 PORT command failure The above message indicates that a connection could not be established. This is a common error for those FTP clients that are behind a firewall. To get around your firewall you may use a passive FTP connection. To enable a passive FTP connection invoke the Ftp#setPassive method prior to invoking the Ftp#connect method. Example: Ftp ftp = new Ftp(hostname, username, password); ftp.setPassive(true); ftp.connect(); 9.2 LOGIN incorrect When attempting to establish a connection to an FTP server you may receive the following error message: Example: 530 Login incorrect The above message indicates that either the username or password is invalid. Check your username and password to be sure that they are correct. If you have verified your username and password are correct and you continue to have problems check the length of your password. Some FTP servers will only accept passwords up to 8 characters in length. If your password is greater than 8 characters in length and you are experiencing login trouble then try limiting your password to the first 8 characters. Example: String username = "jsmith"; String password = "funkyzeit"; String hostname = "10.0.0.2"; Ftp ftp = new Ftp(); ftp.setHostname(hostname); ftp.setUsername(username); // limit password to first 8 characters ftp.setPassword(password.substring(0,8)); // establish connection and login ftp.connect(); 下面在给出实例程序: /* * @(#)FtpExample.java * * Copyright 2001-2002 JScape * 1147 S. 53rd Pl., Mesa, Arizona, 85206, U.S.A. * All rights reserved. * * This software is the confidential and proprietary information of * JScape. ("Confidential Information"). You shall not disclose such * Confidential Information and shall use it only in accordance with * the terms of the license agreement you entered into with JScape. */ import com.jscape.inet.ftp.*; import java.io.*; import java.util.Enumeration; public class FtpExample extends FtpAdapter { private String hostname; private String username; private String password; public FtpExample(String hostname, String username, String password) { this.hostname = hostname; this.username = username; this.password = password; } // print out directory listing public void getListing() throws FtpException { // create new Ftp instance with hostname, username and password arguments Ftp ftp = new Ftp(hostname,username,password); // register this class to capture FTP related events ftp.addFtpListener(this); // connect to FTP server ftp.connect(); // get results of a directory listing String results = ftp.getDirListingAsString(); // print out directory listing results System.out.println(results); // disconnect from FTP server ftp.disconnect(); } // captures connect event public void connected(FtpConnectedEvent evt) { System.out.println("Connected to server: " + evt.getHostname()); } // captures disconnect event public void disconnected(FtpDisconnectedEvent evt) { System.out.println("Disconnected from server: " + evt.getHostname()); } public static void main(String[] args) { String hostname; String username; String password; try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter Ftp hostname (e.g. ftp.microsoft.com): "); hostname = reader.readLine(); System.out.print("Enter username (e.g. anonymous): "); username = reader.readLine(); System.out.print("Enter password (e.g. user@here.com): "); password = reader.readLine(); FtpExample example = new FtpExample(hostname,username,password); example.getListing(); } catch(Exception e) { e.printStackTrace(); } } } |
2.Re [Re: bfcatfriends] | Copy to clipboard |
Posted by: jigsaw Posted on: 2003-08-08 16:15 这种文章给个连接就足够了。。。 |
Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1 客服电话 18559299278 客服信箱 714923@qq.com 客服QQ 714923 |