ftpconnection.java
来自「java ftp 操作代码,程序可以直接运行」· Java 代码 · 共 2,382 行 · 第 1/5 页
JAVA
2,382 行
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */package net.sf.jftp.net;//***now all config files are importedimport java.io.BufferedReader;import java.io.DataInputStream;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.InetAddress;import java.net.ServerSocket;import java.net.UnknownHostException;import java.util.Date;import java.util.StringTokenizer;import java.util.Vector;import javax.swing.JLabel;import javax.swing.JOptionPane;import net.sf.jftp.config.LoadSet;import net.sf.jftp.config.SaveSet;import net.sf.jftp.config.Settings;import net.sf.jftp.system.StringUtils;import net.sf.jftp.system.logging.Log;/** * All control transactions are made here. * See doc/FtpDownload.java for examples and note * that this class is event-driven and not Exception-based! * You might want to take a look at ConnectionListener, too. * * @author David Hansmann, hansmann.d@debitel.net * @version 1.30+, June 2003 */public class FtpConnection implements BasicConnection, FtpConstants{ private static final boolean TESTMODE = false; // everything starting with this will be treated // as a negative response private final static String NEGATIVE = "5"; private final static String NEGATIVE2 = "4"; // everything starting with this will be treated // as a positive response private final static String POSITIVE = "2"; // for resuming private final static String PROCEED = "3"; //"350"; private final static char MORE_LINES_APPENDED = '-'; /** Internal download constant */ public final static String DOWNLOAD = "DOWNLOAD"; /** Internal upload constant */ public final static String UPLOAD = "UPLOAD"; /** Internal abort command constant */ public final static String ABOR = "ABOR"; //*** 1.44: if LIST is not set, then load it from advanced settings //*** And if the file for it is not found, then create it //*** with LIST -laL as the default public static String LIST_DEFAULT = "LIST -laL"; public static String LIST = "default"; public final static String ASCII = "A"; public final static String BINARY = "I"; public final static String EBCDIC = "E"; public final static String L8 = "L 8"; public final static String STREAM = "S"; public final static String BLOCKED = "B"; public final static String COMPRESSED = "C"; private static boolean useStream = true; private static boolean useBlocked = true; private static boolean useCompressed = true; // active ftp ports private static int porta = 5; // 5 * 256 + 1 = 1281 private static int portb = 1; //*** /** * Used to determine the type of transfer. */ public boolean hasUploaded = false; public boolean work = true; private boolean msg = true; private boolean ok = true; private String pwd = ""; private String initCWD = Settings.defaultDir; private String[] loginAck = new String[] { FTP331_USER_OK_NEED_PASSWORD, FTP230_LOGGED_IN }; private String osType = ""; private String dataType; private FtpTransfer lastTransfer = null; private boolean modeStreamSet = false; private DataConnection dcon = null; private Vector listeners = new Vector(); private ConnectionHandler handler = new ConnectionHandler(); // directory downloaded to private String localPath = null; /** the host */ private String host = ""; /** the user */ private String username; /** the password */ private String password; /** the port */ private int port = 21; /** the InputStream of the control connection */ private BufferedReader in; /** the OutputStream of the control connection */ private JConnection jcon; /** we are disconnected */ private boolean connected = false; private boolean shortProgress = false; private boolean isDirUpload = false; private String baseFile; private int fileCount; private String typeNow = ""; private String crlf = null; /** * May contain date listing */ public Vector dateVector = new Vector(); public Vector currentListing = new Vector(); public Vector currentFiles = new Vector(); public Vector currentSizes = new Vector(); public Vector currentPerms = new Vector(); /** * Create an instance with a given host * * @param host The host to connect to */ public FtpConnection(String host) { this.host = host; File f = new File("."); setLocalPath(f.getAbsolutePath()); } /** * Create an instance with a given host, port and initial remote working directory * * @param host The host to connect to * @param port The port used for the control connection, usually 21 * @param initCWD The initial remote working directory */ public FtpConnection(String host, int port, String initCWD) { this.host = host; this.port = port; this.initCWD = initCWD; File f = new File("."); setLocalPath(f.getAbsolutePath()); } /** * Connect to the server an log in. * * Does also fire directory update and connection initialized event if successful or * connection failed event if failed. * * @param username The username * @param password The password * @param initCWD The initial remote working directory * @param crlfx \n, \r, \r\n, CR, LF or CRLF - line break style of the server * @return WRONG_LOGIN_DATA, OFFLINE, GENERIC_FAILED or LOGIN_OK status code */ public FtpConnection(String host, int port, String initCWD, String crlfx) { this.host = host; this.port = port; this.initCWD = initCWD; if(crlfx != null) { if(crlfx.equals("\n") || crlfx.equals("\r") || crlfx.equals("\r\n")) this.crlf = crlfx; crlfx = crlfx.trim().toUpperCase(); if(crlfx.equals("LF")) this.crlf = "\n"; else if(crlfx.equals("CR")) this.crlf = "\r"; else if(crlfx.equals("CRLF")) this.crlf = "\r\n"; } //Log.out("\n\nCRLF:---"+crlf+"---\n\n"); File f = new File("."); setLocalPath(f.getAbsolutePath()); } /** * Connect to the server an log in. * * Does also fire directory update and connection initialized event if successful or * connection failed event if failed. * * @param username The username * @param password The password * @return WRONG_LOGIN_DATA, OFFLINE, GENERIC_FAILED or LOGIN_OK status code */ public int login(String username, String password) { this.username = username; this.password = password; int status = LOGIN_OK; if(msg) { Log.debug("Connecting to " + host); } jcon = new JConnection(host, port); if(jcon.isThere()) { in = jcon.getReader(); if(getLine(POSITIVE) == null)//FTP220_SERVICE_READY) == null) { ok = false; Log.debug("Server closed Connection, maybe too many users..."); status = OFFLINE; } if(msg) { Log.debug("Connection established..."); } jcon.send(USER + " " + username); if(!getLine(loginAck).startsWith(POSITIVE))//FTP230_LOGGED_IN)) { jcon.send(PASS + " " + password); if(success(POSITIVE))//FTP230_LOGGED_IN)) { if(msg) { Log.debug("Logged in..."); } } else { Log.debug("Wrong password!"); ok = false; status = WRONG_LOGIN_DATA; } } // end if(jcon)... } else { if(msg) { Log.debug("FTP not available!"); ok = false; status = GENERIC_FAILED; } } if(ok) { connected = true; system(); //if(getOsType().indexOf("MVS") < 0) binary(); if(initCWD.trim().equals(Settings.defaultDir) || !chdirNoRefresh(initCWD)) { //System.out.println("default dir..."); //if(!chdirNoRefresh(getPWD())) //{ //System.out.println("FtpConnection should not do this..."); // if(!chdirNoRefresh("~")) // { // chdirNoRefresh("/"); // } //} updatePWD(); } //Array of length 6 created, as that is maximum LoadSet size (need //public variable with that constant there for it to refer to?) String[] advSettings = new String[6]; if(getOsType().indexOf("OS/2") >= 0) { LIST_DEFAULT = "LIST"; } if(LIST.equals("default")) { //just get the first item (somehow it knows first is the //FTP list command) advSettings = LoadSet.loadSet(Settings.adv_settings); //*** IF FILE NOT FOUND, CREATE IT AND SET IT TO LIST_DEFAULT if(advSettings == null) { LIST = LIST_DEFAULT; SaveSet s = new SaveSet(Settings.adv_settings, LIST); } else { LIST = advSettings[0]; if(LIST == null) { LIST = LIST_DEFAULT; } } } if(getOsType().indexOf("MVS") >= 0) { LIST = "LIST"; } //*** fireDirectoryUpdate(this); fireConnectionInitialized(this); } else { fireConnectionFailed(this, new Integer(status).toString()); } return status; } /** * Sort the filesizes an return an array. * * The Array should be in sync with the other sort*-Methods * * @return An String-array of sizes containing the size or -1 if failed or 0 for directories */ public String[] sortSize() { try { currentSizes.removeAllElements(); for(int i=0; i<currentListing.size(); i++) { String tmp = (String) currentListing.get(i); // ------------- VMS override ------------------- if(getOsType().indexOf("VMS") >= 0) { if(tmp.indexOf(";") < 0) { continue; } currentSizes.add("-1"); continue; } // ------------- MVS override ------------------- if(getOsType().indexOf("MVS") >= 0) { if(tmp.startsWith("Volume") || (tmp.indexOf(" ") < 0)) { continue; } currentSizes.add("-1"); continue; } // ------------------------------------------------ else if(getOsType().indexOf("WINDOW") >= 0) { StringTokenizer to = new StringTokenizer(tmp, " ", false); if(to.countTokens() >= 4) { to.nextToken(); to.nextToken(); String size = to.nextToken(); if(size.equals("<DIR>")) { currentSizes.add("0"); } else { try { Long.parseLong(size); currentSizes.add(size); } catch(Exception ex) { currentSizes.add("-1"); Log.out("WARNING: filesize can not be determined - value is " + size); } } } } // ------------------------------------------------ else if(getOsType().indexOf("OS/2") >= 0) { StringTokenizer to = new StringTokenizer(tmp, " ", false); tmp = giveSize(to, 0); Log.out("OS/2 parser (size): " + tmp); currentSizes.add(tmp); } else { //Log.out("\n\nparser\n\n"); StringTokenizer to = new StringTokenizer(tmp, " ", false); if(to.countTokens() >= 8) // unix { tmp = giveSize(to, 4); currentSizes.add(tmp); //Log.out(tmp); } else if(to.countTokens() == 7) // unix, too { Log.out("WARNING: 7 token backup size parser activated!"); tmp = giveSize(to, 4); currentSizes.add(tmp); } else { Log.debug("cannot parse line: " + tmp); } } } } catch(Exception ex)
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?