📄 ftpclient.java
字号:
/**
* Constructor. Creates the control
* socket. Allows setting of control port (normally
* set by default to 21).
*
* @param remoteAddr the address of the
* remote host
* @param controlPort port for control stream
*/
public FTPClient(InetAddress remoteAddr, int controlPort)
throws IOException, FTPException {
this(remoteAddr, controlPort, 0);
}
/**
* Constructor. Creates the control
* socket. Allows setting of control port (normally
* set by default to 21).
*
* @param remoteAddr the address of the
* remote host
* @param controlPort port for control stream (-1 for default port)
* @param timeout the length of the timeout, in milliseconds
* (pass in 0 for no timeout)
*/
public FTPClient(InetAddress remoteAddr, int controlPort, int timeout)
throws IOException, FTPException {
if (controlPort < 0)
controlPort = FTPControlSocket.CONTROL_PORT;
initialize(new FTPControlSocket(remoteAddr, controlPort, timeout, DEFAULT_ENCODING, null));
}
/**
* Constructor. Creates the control
* socket. Allows setting of control port (normally
* set by default to 21).
*
* @param remoteAddr the address of the
* remote host
* @param controlPort port for control stream (-1 for default port)
* @param timeout the length of the timeout, in milliseconds
* (pass in 0 for no timeout)
* @param encoding character encoding used for data
*/
public FTPClient(InetAddress remoteAddr, int controlPort, int timeout, String encoding)
throws IOException, FTPException {
if (controlPort < 0)
controlPort = FTPControlSocket.CONTROL_PORT;
initialize(new FTPControlSocket(remoteAddr, controlPort, timeout, encoding, null));
}
/**
* Default constructor for use by subclasses
*/
protected FTPClient() {
}
/**
* Checks if the client has connected to the server and throws an exception if it hasn't.
* This is only intended to be used by subclasses
*
* @throws FTPException Thrown if the client has not connected to the server.
*/
protected void checkConnection(boolean shouldBeConnected) throws FTPException {
if (shouldBeConnected && control==null)
throw new FTPException("The FTP client has not yet connected to the server. "
+ "The requested action cannot be performed until after a connection has been established.");
else if (!shouldBeConnected && control!=null)
throw new FTPException("The FTP client has already been connected to the server. "
+"The requested action must be performed before a connection is established.");
}
/**
* Set the control socket explicitly
*
* @param control control socket reference
*/
protected void initialize(FTPControlSocket control) {
this.control = control;
control.setMessageListener(messageListener);
}
/**
* Switch debug of responses on or off
*
* @param on true if you wish to have responses to
* the log stream, false otherwise
* @deprecated use the Logger class to switch debugging on and off
*/
public void debugResponses(boolean on) {
if (on)
Logger.setLevel(Level.DEBUG);
else
Logger.setLevel(Level.OFF);
}
/**
* Set strict checking of FTP return codes. If strict
* checking is on (the default) code must exactly match the expected
* code. If strict checking is off, only the first digit must match.
*
* @param strict true for strict checking, false for loose checking
*/
public void setStrictReturnCodes(boolean strict) {
this.strictReturnCodes = strict;
if (control != null)
control.setStrictReturnCodes(strict);
}
/**
* Determine if strict checking of return codes is switched on. If it is
* (the default), all return codes must exactly match the expected code.
* If strict checking is off, only the first digit must match.
*
* @return true if strict return code checking, false if non-strict.
*/
public boolean isStrictReturnCodes() {
return strictReturnCodes;
}
/**
* Set the TCP timeout on the underlying socket.
*
* If a timeout is set, then any operation which
* takes longer than the timeout value will be
* killed with a java.io.InterruptedException. We
* set both the control and data connections
*
* @param millis The length of the timeout, in milliseconds
*/
public void setTimeout(int millis)
throws IOException {
this.timeout = millis;
control.setTimeout(millis);
}
/**
* Set the connect mode
*
* @param mode ACTIVE or PASV mode
*/
public void setConnectMode(FTPConnectMode mode) {
connectMode = mode;
}
/**
* Set a listener that handles all FTP messages
*
* @param listener message listener
*/
public void setMessageListener(FTPMessageListener listener) {
this.messageListener = listener;
if (control != null)
control.setMessageListener(listener);
}
/**
* Set a progress monitor for callbacks. The bytes transferred in
* between callbacks is only indicative. In many cases, the data is
* read in chunks, and if the interval is set to be smaller than the
* chunk size, the callback will occur after after chunk transfer rather
* than the interval.
*
* @param monitor the monitor object
* @param interval bytes transferred in between callbacks
*/
public void setProgressMonitor(FTPProgressMonitor monitor, long interval) {
this.monitor = monitor;
this.monitorInterval = interval;
}
/**
* Set a progress monitor for callbacks. Uses default callback
* interval
*
* @param monitor the monitor object
*/
public void setProgressMonitor(FTPProgressMonitor monitor) {
this.monitor = monitor;
}
/**
* Get the bytes transferred between each callback on the
* progress monitor
*
* @return long bytes to be transferred before a callback
*/
public long getMonitorInterval() {
return monitorInterval;
}
/**
* Set the size of the buffers used in writing to and reading from
* the data sockets
*
* @param size new size of buffer
*/
public void setTransferBufferSize(int size) {
transferBufferSize = size;
}
/**
* Get the size of the buffers used in writing to and reading from
* the data sockets
*
* @return transfer buffer size
*/
public int getTransferBufferSize() {
return transferBufferSize;
}
/**
* Cancels the current transfer. Generally called from a separate
* thread. Note that this may leave partially written files on the
* server or on local disk, and should not be used unless absolutely
* necessary. The server is not notified
*/
public void cancelTransfer() {
cancelTransfer = true;
}
/**
* Login into an account on the FTP server. This
* call completes the entire login process
*
* @param user user name
* @param password user's password
*/
public void login(String user, String password)
throws IOException, FTPException {
checkConnection(true);
FTPReply reply = control.sendCommand("USER " + user);
// we allow for a site with no password - 230 response
String[] validCodes = {"230", "331"};
lastValidReply = control.validateReply(reply, validCodes);
if (lastValidReply.getReplyCode().equals("230"))
return;
else {
password(password);
}
}
/**
* Supply the user name to log into an account
* on the FTP server. Must be followed by the
* password() method - but we allow for
*
* @param user user name
*/
public void user(String user)
throws IOException, FTPException {
checkConnection(true);
FTPReply reply = control.sendCommand("USER " + user);
// we allow for a site with no password - 230 response
String[] validCodes = {"230", "331"};
lastValidReply = control.validateReply(reply, validCodes);
}
/**
* Supplies the password for a previously supplied
* username to log into the FTP server. Must be
* preceeded by the user() method
*
* @param password The password.
*/
public void password(String password)
throws IOException, FTPException {
checkConnection(true);
FTPReply reply = control.sendCommand("PASS " + password);
// we allow for a site with no passwords (202)
String[] validCodes = {"230", "202"};
lastValidReply = control.validateReply(reply, validCodes);
}
/**
* Set up SOCKS v4/v5 proxy settings. This can be used if there
* is a SOCKS proxy server in place that must be connected thru.
* Note that setting these properties directs <b>all</b> TCP
* sockets in this JVM to the SOCKS proxy
*
* @param port SOCKS proxy port
* @param host SOCKS proxy hostname
*/
public static void initSOCKS(String port, String host) {
Properties props = System.getProperties();
props.put(SOCKS_PORT, port);
props.put(SOCKS_HOST, host);
System.setProperties(props);
}
/**
* Set up SOCKS username and password for SOCKS username/password
* authentication. Often, no authentication will be required
* but the SOCKS server may be configured to request these.
*
* @param username the SOCKS username
* @param password the SOCKS password
*/
public static void initSOCKSAuthentication(String username,
String password) {
Properties props = System.getProperties();
props.put("java.net.socks.username", username);
props.put("java.net.socks.password", password);
System.setProperties(props);
}
/**
* Clear SOCKS settings. Note that setting these properties affects
* <b>all</b> TCP sockets in this JVM
*/
public static void clearSOCKS() {
Properties prop = System.getProperties();
prop.remove(SOCKS_HOST);
prop.remove(SOCKS_PORT);
System.setProperties(prop);
}
/**
* Get the name of the remote host
*
* @return remote host name
*/
String getRemoteHostName() {
return control.getRemoteHostName();
}
/**
* Issue arbitrary ftp commands to the FTP server.
*
* @param command ftp command to be sent to server
* @param validCodes valid return codes for this command
*
* @return the text returned by the FTP server
*/
public String quote(String command, String[] validCodes)
throws IOException, FTPException {
checkConnection(true);
FTPReply reply = control.sendCommand(command);
// allow for no validation to be supplied
if (validCodes != null && validCodes.length > 0) {
lastValidReply = control.validateReply(reply, validCodes);
return lastValidReply.getReplyText();
}
else {
throw new FTPException("Valid reply code must be supplied");
}
}
/**
* Get the size of a remote file. This is not a standard FTP command, it
* is defined in "Extensions to FTP", a draft RFC
* (draft-ietf-ftpext-mlst-16.txt)
*
* @param remoteFile name or path of remote file in current directory
* @return size of file in bytes
*/
public long size(String remoteFile)
throws IOException, FTPException {
checkConnection(true);
FTPReply reply = control.sendCommand("SIZE " + remoteFile);
lastValidReply = control.validateReply(reply, "213");
// parse the reply string .
String replyText = lastValidReply.getReplyText();
// trim off any trailing characters after a space, e.g. webstar
// responds to SIZE with 213 55564 bytes
int spacePos = replyText.indexOf(' ');
if (spacePos >= 0)
replyText = replyText.substring(0, spacePos);
// parse the reply
try {
return Long.parseLong(replyText);
}
catch (NumberFormatException ex) {
throw new FTPException("Failed to parse reply: " + replyText);
}
}
/**
* Make the next file transfer (put or get) resume. For puts(), the
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -