org.apache.commons.net.ftp下的FTPClient这个类,然后读取文件,进行解析。发现读取到355行就卡住不动了。
分析发现,直接使用io流读取没有任何问题,大文件也可以读取,所以问题锁定FTPClient的文件流读取有问题。首先将文件的每行减少字符串长度,发现,读取的行数变多,所以定位为缓冲区大小的问题。然后找到FTPClient源码,如下:
public FTPClient()
{
__initDefaults();
__dataTimeout = -1;
__remoteVerificationEnabled = true;
__parserFactory = new DefaultFTPFileEntryParserFactory();
__configuration = null;
}
private void __initDefaults()
{
__dataConnectionMode = ACTIVE_LOCAL_DATA_CONNECTION_MODE;
__passiveHost = null;
__passivePort = -1;
__fileType = FTP.ASCII_FILE_TYPE;
__fileStructure = FTP.FILE_STRUCTURE;
__fileFormat = FTP.NON_PRINT_TEXT_FORMAT;
__fileTransferMode = FTP.STREAM_TRANSFER_MODE;
__restartOffset = 0;
__systemName = null;
__entryParser = null;
__bufferSize = Util.DEFAULT_COPY_BUFFER_SIZE;
}
__bufferSize = Util.DEFAULT_COPY_BUFFER_SIZE;
发现这一行设置缓冲区大小的时候是Util类的变量来控制的,然后找到package org.apache.commons.net.ftp;这个包下的Util类,
代码如下:
public final class Util
{
public static final int DEFAULT_COPY_BUFFER_SIZE = 1024;
// Cannot be instantiated
private Util()
{ }
.....
发现,该值写死了!!不可更改!
正式该部分的处理,导致FTPClient设置缓冲区大小的部分不起作用。
好吧,只好放弃工具类,自己实现一个了
以下是我自己实现的:
package com.ideal.crm.star.utils;
import java.io.ByteArrayInputStream;
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 java.net.SocketException;
import org.apache.commons.net.ftp.FTPReply;
import com.ideal.crm.common.exception.FTPClientException;
import com.ideal.crm.common.log.ILogger;
import com.ideal.crm.common.log.LoggerFactory;
import com.ideal.crm.common.utils.PropertiesUtil;
/**
* FTP工具类
*/
public class CustFTPUtils {
private static final ILogger log = LoggerFactory
.getLogger(CustFTPUtils.class);
private String host;
private int port;
private String username;
private String password;
private boolean binaryTransfer = true;
private boolean passiveMode = true;
private String encoding = "UTF-8";
private int clientTimeout = 1000 * 30;
private String PROPERTIES_FILE = "conf/ftp_files.properties";
private static class FTPUtilsHolder {
private static CustFTPUtils instance = new CustFTPUtils();
}
public static CustFTPUtils getInstance() {
return FTPUtilsHolder.instance;
}
private CustFTPUtils() {
host = PropertiesUtil.getConfigValueCache(PROPERTIES_FILE, "ftp.host");
port = PropertiesUtil.getIntFromConfigValueCache(PROPERTIES_FILE, "ftp.port");
username = PropertiesUtil.getConfigValueCache(PROPERTIES_FILE, "ftp.username");
password = PropertiesUtil.getConfigValueCache(PROPERTIES_FILE, "ftp.password");
}
/**
* 返回一个FTPClient实例
*
* @throws FTPClientException
*/
private FTPClient getFTPClient() throws FTPClientException {
FTPClient ftpClient = new FTPClient(); // 构造一个FtpClient实例
/** 由于FTPClient读取的缓存 内部使用的是Util工具的 **/
ftpClient.setControlEncoding(encoding); // 设置字符集
//被动模式+超时时间设置,解决卡死的问题 jiao_zg 注
ftpClient.setDefaultTimeout(clientTimeout * 1000);
ftpClient.setBufferSize(1024*1024*1024);
ftpClient.setDataTimeout(clientTimeout * 1000);
connect(ftpClient); // 连接到ftp服务器
// 设置为passive模式
if (passiveMode) {
ftpClient.enterLocalPassiveMode();
}
setFileType(ftpClient); // 设置文件传输类型
try {
ftpClient.setSoTimeout(clientTimeout);
} catch (SocketException e) {
throw new FTPClientException("Set timeout error.", e);
}
return ftpClient;
}
/**
* 设置文件传输类型
*
* @throws FTPClientException
* @throws IOException
*/
private void setFileType(FTPClient ftpClient) throws FTPClientException {
try {
if (binaryTransfer) {
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
} else {
ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE);
}
} catch (IOException e) {
throw new FTPClientException("Could not to set file type.", e);
}
}
/**
* 连接到ftp服务器
*
* @param ftpClient
* @return 连接成功返回true,否则返回false
* @throws FTPClientException
*/
private boolean connect(FTPClient ftpClient) throws FTPClientException {
try {
ftpClient.connect(host, port);
// 连接后检测返回码来校验连接是否成功
int reply = ftpClient.getReplyCode();
if (FTPReply.isPositiveCompletion(reply)) {
// 登陆到ftp服务器
if (ftpClient.login(username, password)) {
setFileType(ftpClient);
return true;
}
} else {
throw new FTPClientException("FTP server refused connection.");
}
} catch (IOException e) {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect(); // 断开连接
} catch (IOException e1) {
throw new FTPClientException(
"Could not disconnect from server.", e1);
}
}
throw new FTPClientException("Could not connect to server.", e);
}
return false;
}
// ---------------------------------------------------------------------
// public method
// ---------------------------------------------------------------------
/**
* 断开ftp连接
*
* @throws FTPClientException
*/
public void disconnect() throws FTPClientException {
try {
FTPClient ftpClient = getFTPClient();
ftpClient.logout();
if (ftpClient.isConnected()) {
ftpClient.disconnect();
ftpClient = null;
}
} catch (IOException e) {
throw new FTPClientException("Could not disconnect from server.",
e);
}
}
public boolean mkdir(String pathname) throws FTPClientException {
return mkdir(pathname, null);
}
/**
* 在ftp服务器端创建目录(不支持一次创建多级目录)
*
* 该方法执行完后将自动关闭当前连接
*
* @param pathname
* @return
* @throws FTPClientException
*/
public boolean mkdir(String pathname, String workingDirectory)
throws FTPClientException {
return mkdir(pathname, workingDirectory, true);
}
/**
* 在ftp服务器端创建目录(不支持一次创建多级目录)
*
* @param pathname
* @param autoClose
* 是否自动关闭当前连接
* @return
* @throws FTPClientException
*/
public boolean mkdir(String pathname, String workingDirectory,
boolean autoClose) throws FTPClientException {
try {
getFTPClient().changeWorkingDirectory(workingDirectory);
return getFTPClient().makeDirectory(pathname);
} catch (IOException e) {
throw new FTPClientException("Could not mkdir.", e);
} finally {
if (autoClose) {
disconnect(); // 断开连接
}
}
}
/**
* 上传一个本地文件到远程指定文件
*
* @param remoteAbsoluteFile
* 远程文件名(包括完整路径)
* @param localAbsoluteFile
* 本地文件名(包括完整路径)
* @return 成功时,返回true,失败返回false
* @throws FTPClientException
*/
public boolean put(String remoteAbsoluteFile, String localAbsoluteFile)
throws FTPClientException {
return put(remoteAbsoluteFile, localAbsoluteFile, true);
}
/**
* 上传一个本地文件到远程指定文件
*
* @param remoteAbsoluteFile
* 远程文件名(包括完整路径)
* @param localAbsoluteFile
* 本地文件名(包括完整路径)
* @param autoClose
* 是否自动关闭当前连接
* @return 成功时,返回true,失败返回false
* @throws FTPClientException
*/
public boolean put(String remoteAbsoluteFile, String localAbsoluteFile,
boolean autoClose) throws FTPClientException {
InputStream input = null;
try {
// 处理传输
input = new FileInputStream(localAbsoluteFile);
getFTPClient().storeFile(remoteAbsoluteFile, input);
log.debug("put " + localAbsoluteFile);
return true;
} catch (FileNotFoundException e) {
throw new FTPClientException("local file not found.", e);
} catch (IOException e) {
throw new FTPClientException("Could not put file to server.", e);
} finally {
try {
if (input != null) {
input.close();
}
} catch (Exception e) {
throw new FTPClientException("Couldn't close FileInputStream.",
e);
}
if (autoClose) {
disconnect(); // 断开连接
}
}
}
/**
* 上传本地数据到远程指定文件
*
* @param remoteAbsoluteFile
* 远程文件名(包括完整路径)
* @param content
* 文件内容
* @return 成功时,返回true,失败返回false
* @throws FTPClientException
*/
public boolean put(String remoteAbsoluteFile, byte[] content) throws FTPClientException {
return put(remoteAbsoluteFile, content, false);
}
/**
* 上传本地数据到远程指定文件
*
* @param remoteAbsoluteFile
* 远程文件名(包括完整路径)
* @param content
* 文件内容
* @param autoClose
* 是否自动关闭当前连接
* @return 成功时,返回true,失败返回false
* @throws FTPClientException
*/
public boolean put(String remoteAbsoluteFile, byte[] content,
boolean autoClose) throws FTPClientException {
InputStream input = null;
try {
// 处理传输
input = new ByteArrayInputStream(content);
getFTPClient().storeFile(remoteAbsoluteFile, input);
return true;
} catch (IOException e) {
throw new FTPClientException("Could not put file to server.", e);
} finally {
try {
if (input != null) {
input.close();
}
} catch (Exception e) {
throw new FTPClientException("Couldn't close FileInputStream.",
e);
}
if (autoClose) {
disconnect(); // 断开连接
}
}
}
/**
* 下载一个远程文件到本地的指定文件
*
* @param remoteAbsoluteFile
* 远程文件名(包括完整路径)
* @param localAbsoluteFile
* 本地文件名(包括完整路径)
* @return 成功时,返回true,失败返回false
* @throws FTPClientException
*/
public boolean get(String remoteAbsoluteFile, String localAbsoluteFile)
throws FTPClientException {
return get(remoteAbsoluteFile, localAbsoluteFile, true);
}
/**
* 下载一个远程文件到本地的指定文件
*
* @param remoteAbsoluteFile
* 远程文件名(包括完整路径)
* @param localAbsoluteFile
* 本地文件名(包括完整路径)
* @param autoClose
* 是否自动关闭当前连接
*
* @return 成功时,返回true,失败返回false
* @throws FTPClientException
*/
public boolean get(String remoteAbsoluteFile, String localAbsoluteFile,
boolean autoClose) throws FTPClientException {
OutputStream output = null;
try {
output = new FileOutputStream(localAbsoluteFile);
return get(remoteAbsoluteFile, output, autoClose);
} catch (FileNotFoundException e) {
throw new FTPClientException("local file not found.", e);
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
throw new FTPClientException("Couldn't close FileOutputStream.",
e);
}
}
}
/**
* 下载一个远程文件到指定的流 处理完后记得关闭流
*
* @param remoteAbsoluteFile
* @param output
* @return
* @throws FTPClientException
*/
public boolean get(String remoteAbsoluteFile, OutputStream output)
throws FTPClientException {
return get(remoteAbsoluteFile, output, true);
}
/**
* 下载一个远程文件到指定的流 处理完后记得关闭流
*
* @param remoteAbsoluteFile
* @param output
* @param delFile
* @return
* @throws FTPClientException
*/
public boolean get(String remoteAbsoluteFile, OutputStream output,
boolean autoClose) throws FTPClientException {
try {
FTPClient ftpClient = getFTPClient();
// 处理传输
return ftpClient.retrieveFile(remoteAbsoluteFile, output);
} catch (IOException e) {
throw new FTPClientException("Couldn't get file from server.", e);
} finally {
if (autoClose) {
disconnect(); // 关闭链接
}
}
}
/**
* 下载一个远程文件到指定的流 处理完后记得关闭流
*
* @param remoteAbsoluteFile
* @param delFile
* @return
* @throws FTPClientException
*/
public InputStream get(String remoteAbsoluteFile,
boolean autoClose) throws FTPClientException {
try {
FTPClient ftpClient = getFTPClient();
ftpClient.setBufferSize(1024*1024*1024);
// 处理传输
return ftpClient.retrieveFileStream(remoteAbsoluteFile);
} catch (IOException e) {
System.out.println("关闭连接");
disconnect(); // 关闭链接
throw new FTPClientException("Couldn't get file from server.", e);
} finally {
if (autoClose) {
System.out.println("关闭连接");
disconnect(); // 关闭链接
}
}
}
/**
* 从ftp服务器上删除一个文件 该方法将自动关闭当前连接
*
* @param delFile
* @return
* @throws FTPClientException
*/
public boolean delete(String delFile) throws FTPClientException {
return delete(delFile, true);
}
/**
* 从ftp服务器上删除一个文件
*
* @param delFile
* @param autoClose
* 是否自动关闭当前连接
*
* @return
* @throws FTPClientException
*/
public boolean delete(String delFile, boolean autoClose)
throws FTPClientException {
try {
getFTPClient().deleteFile(delFile);
return true;
} catch (IOException e) {
throw new FTPClientException("Couldn't delete file from server.",
e);
} finally {
if (autoClose) {
disconnect(); // 关闭链接
}
}
}
/**
* 批量删除 该方法将自动关闭当前连接
*
* @param delFiles
* @return
* @throws FTPClientException
*/
public boolean delete(String[] delFiles) throws FTPClientException {
return delete(delFiles, true);
}
/**
* 批量删除
*
* @param delFiles
* @param autoClose
* 是否自动关闭当前连接
*
* @return
* @throws FTPClientException
*/
public boolean delete(String[] delFiles, boolean autoClose)
throws FTPClientException {
try {
FTPClient ftpClient = getFTPClient();
for (String s : delFiles) {
ftpClient.deleteFile(s);
}
return true;
} catch (IOException e) {
throw new FTPClientException("Couldn't delete file from server.",
e);
} finally {
if (autoClose) {
disconnect(); // 关闭链接
}
}
}
public boolean isExist(String remoteAbsoluteFile) throws FTPClientException {
return false;
}
/**
* 列出远程默认目录下所有的文件
*
* @return 远程默认目录下所有文件名的列表,目录不存在或者目录下没有文件时返回0长度的数组
* @throws FTPClientException
*/
public String[] listNames() throws FTPClientException {
return listNames(null, true);
}
public String[] listNames(boolean autoClose) throws FTPClientException {
return listNames(null, autoClose);
}
/**
* 列出远程目录下所有的文件
*
* @param remotePath
* 远程目录名
* @param autoClose
* 是否自动关闭当前连接
*
* @return 远程目录下所有文件名的列表,目录不存在或者目录下没有文件时返回0长度的数组
* @throws FTPClientException
*/
public String[] listNames(String remotePath, boolean autoClose)
throws FTPClientException {
try {
String[] listNames = getFTPClient().listNames(remotePath);
return listNames;
} catch (IOException e) {
throw new FTPClientException("列出远程目录下所有的文件时出现异常", e);
} finally {
if (autoClose) {
disconnect(); // 关闭链接
}
}
}
}
package com.ideal.crm.star.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
import org.apache.commons.net.MalformedServerReplyException;
import org.apache.commons.net.ftp.Configurable;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPCommand;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPFileEntryParser;
import org.apache.commons.net.ftp.FTPFileList;
import org.apache.commons.net.ftp.FTPFileListParser;
import org.apache.commons.net.ftp.FTPListParseEngine;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory;
import org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory;
import org.apache.commons.net.ftp.parser.ParserInitializationException;
import org.apache.commons.net.io.CopyStreamEvent;
import org.apache.commons.net.io.CopyStreamException;
import org.apache.commons.net.io.FromNetASCIIInputStream;
import org.apache.commons.net.io.ToNetASCIIOutputStream;
import org.apache.commons.net.io.Util;
public class FTPClient extends FTP
implements Configurable
{
public static final int ACTIVE_LOCAL_DATA_CONNECTION_MODE = 0;
public static final int ACTIVE_REMOTE_DATA_CONNECTION_MODE = 1;
public static final int PASSIVE_LOCAL_DATA_CONNECTION_MODE = 2;
public static final int PASSIVE_REMOTE_DATA_CONNECTION_MODE = 3;
private int __dataConnectionMode, __dataTimeout;
private int __passivePort;
private String __passiveHost;
private int __fileType, __fileFormat, __fileStructure, __fileTransferMode;
private boolean __remoteVerificationEnabled;
private long __restartOffset;
private FTPFileEntryParserFactory __parserFactory;
private int __bufferSize=1024*1024*1024;
private String __systemName;
private FTPFileEntryParser __entryParser;
private FTPClientConfig __configuration;
public FTPClient()
{
__initDefaults();
__dataTimeout = -1;
__remoteVerificationEnabled = true;
__parserFactory = new DefaultFTPFileEntryParserFactory();
__configuration = null;
}
private void __initDefaults()
{
__dataConnectionMode = ACTIVE_LOCAL_DATA_CONNECTION_MODE;
__passiveHost = null;
__passivePort = -1;
__fileType = FTP.ASCII_FILE_TYPE;
__fileStructure = FTP.FILE_STRUCTURE;
__fileFormat = FTP.NON_PRINT_TEXT_FORMAT;
__fileTransferMode = FTP.STREAM_TRANSFER_MODE;
__restartOffset = 0;
__systemName = null;
__entryParser = null;
__bufferSize = __bufferSize;
}
private String __parsePathname(String reply)
{
int begin, end;
begin = reply.indexOf('"') + 1;
end = reply.indexOf('"', begin);
return reply.substring(begin, end);
}
private void __parsePassiveModeReply(String reply)
throws MalformedServerReplyException
{
int i, index, lastIndex;
String octet1, octet2;
StringBuffer host;
reply = reply.substring(reply.indexOf('(') + 1,
reply.indexOf(')')).trim();
host = new StringBuffer(24);
lastIndex = 0;
index = reply.indexOf(',');
host.append(reply.substring(lastIndex, index));
for (i = 0; i < 3; i++)
{
host.append('.');
lastIndex = index + 1;
index = reply.indexOf(',', lastIndex);
host.append(reply.substring(lastIndex, index));
}
lastIndex = index + 1;
index = reply.indexOf(',', lastIndex);
octet1 = reply.substring(lastIndex, index);
octet2 = reply.substring(index + 1);
// index and lastIndex now used as temporaries
try
{
index = Integer.parseInt(octet1);
lastIndex = Integer.parseInt(octet2);
}
catch (NumberFormatException e)
{
throw new MalformedServerReplyException(
"Could not parse passive host information.\nServer Reply: " + reply);
}
index <<= 8;
index |= lastIndex;
__passiveHost = host.toString();
__passivePort = index;
}
private boolean __storeFile(int command, String remote, InputStream local)
throws IOException
{
OutputStream output;
Socket socket;
if ((socket = _openDataConnection_(command, remote)) == null)
return false;
output = new BufferedOutputStream(socket.getOutputStream(),
getBufferSize()
);
if (__fileType == ASCII_FILE_TYPE)
output = new ToNetASCIIOutputStream(output);
// Treat everything else as binary for now
try
{
Util.copyStream(local, output, getBufferSize(),
CopyStreamEvent.UNKNOWN_STREAM_SIZE, null,
false);
}
catch (IOException e)
{
try
{
socket.close();
}
catch (IOException f)
{}
throw e;
}
output.close();
socket.close();
return completePendingCommand();
}
private OutputStream __storeFileStream(int command, String remote)
throws IOException
{
OutputStream output;
Socket socket;
if ((socket = _openDataConnection_(command, remote)) == null)
return null;
output = socket.getOutputStream();
if (__fileType == ASCII_FILE_TYPE) {
// We buffer ascii transfers because the buffering has to
// be interposed between ToNetASCIIOutputSream and the underlying
// socket output stream. We don't buffer binary transfers
// because we don't want to impose a buffering policy on the
// programmer if possible. Programmers can decide on their
// own if they want to wrap the SocketOutputStream we return
// for file types other than ASCII.
output = new BufferedOutputStream(output,
getBufferSize());
output = new ToNetASCIIOutputStream(output);
}
return new org.apache.commons.net.io.SocketOutputStream(socket, output);
}
protected Socket _openDataConnection_(int command, String arg)
throws IOException
{
Socket socket;
if (__dataConnectionMode != ACTIVE_LOCAL_DATA_CONNECTION_MODE &&
__dataConnectionMode != PASSIVE_LOCAL_DATA_CONNECTION_MODE)
return null;
if (__dataConnectionMode == ACTIVE_LOCAL_DATA_CONNECTION_MODE)
{
ServerSocket server;
server = _socketFactory_.createServerSocket(0, 1, getLocalAddress());
if (!FTPReply.isPositiveCompletion(port(getLocalAddress(),
server.getLocalPort())))
{
server.close();
return null;
}
if ((__restartOffset > 0) && !restart(__restartOffset))
{
server.close();
return null;
}
if (!FTPReply.isPositivePreliminary(sendCommand(command, arg)))
{
server.close();
return null;
}
// For now, let's just use the data timeout value for waiting for
// the data connection. It may be desirable to let this be a
// separately configurable value. In any case, we really want
// to allow preventing the accept from blocking indefinitely.
if (__dataTimeout >= 0)
server.setSoTimeout(__dataTimeout);
socket = server.accept();
server.close();
}
else
{ // We must be in PASSIVE_LOCAL_DATA_CONNECTION_MODE
if (pasv() != FTPReply.ENTERING_PASSIVE_MODE)
return null;
__parsePassiveModeReply((String)_replyLines.elementAt(0));
socket = _socketFactory_.createSocket(__passiveHost, __passivePort);
if ((__restartOffset > 0) && !restart(__restartOffset))
{
socket.close();
return null;
}
if (!FTPReply.isPositivePreliminary(sendCommand(command, arg)))
{
socket.close();
return null;
}
}
if (__remoteVerificationEnabled && !verifyRemote(socket))
{
InetAddress host1, host2;
host1 = socket.getInetAddress();
host2 = getRemoteAddress();
socket.close();
throw new IOException(
"Host attempting data connection " + host1.getHostAddress() +
" is not same as server " + host2.getHostAddress());
}
if (__dataTimeout >= 0)
socket.setSoTimeout(__dataTimeout);
return socket;
}
protected void _connectAction_() throws IOException
{
super._connectAction_();
__initDefaults();
}
public void setDataTimeout(int timeout)
{
__dataTimeout = timeout;
}
public void setParserFactory(FTPFileEntryParserFactory parserFactory) {
__parserFactory = parserFactory;
}
public void disconnect() throws IOException
{
super.disconnect();
__initDefaults();
}
public void setRemoteVerificationEnabled(boolean enable)
{
__remoteVerificationEnabled = enable;
}
public boolean isRemoteVerificationEnabled()
{
return __remoteVerificationEnabled;
}
public boolean login(String username, String password) throws IOException
{
user(username);
if (FTPReply.isPositiveCompletion(_replyCode))
return true;
// If we get here, we either have an error code, or an intermmediate
// reply requesting password.
if (!FTPReply.isPositiveIntermediate(_replyCode))
return false;
return FTPReply.isPositiveCompletion(pass(password));
}
public boolean login(String username, String password, String account)
throws IOException
{
user(username);
if (FTPReply.isPositiveCompletion(_replyCode))
return true;
// If we get here, we either have an error code, or an intermmediate
// reply requesting password.
if (!FTPReply.isPositiveIntermediate(_replyCode))
return false;
pass(password);
if (FTPReply.isPositiveCompletion(_replyCode))
return true;
if (!FTPReply.isPositiveIntermediate(_replyCode))
return false;
return FTPReply.isPositiveCompletion(acct(account));
}
public boolean logout() throws IOException
{
return FTPReply.isPositiveCompletion(quit());
}
public boolean changeWorkingDirectory(String pathname) throws IOException
{
return FTPReply.isPositiveCompletion(cwd(pathname));
}
public boolean changeToParentDirectory() throws IOException
{
return FTPReply.isPositiveCompletion(cdup());
}
public boolean structureMount(String pathname) throws IOException
{
return FTPReply.isPositiveCompletion(smnt(pathname));
}
boolean reinitialize() throws IOException
{
rein();
if (FTPReply.isPositiveCompletion(_replyCode) ||
(FTPReply.isPositivePreliminary(_replyCode) &&
FTPReply.isPositiveCompletion(getReply())))
{
__initDefaults();
return true;
}
return false;
}
public void enterLocalActiveMode()
{
__dataConnectionMode = ACTIVE_LOCAL_DATA_CONNECTION_MODE;
__passiveHost = null;
__passivePort = -1;
}
public void enterLocalPassiveMode()
{
__dataConnectionMode = PASSIVE_LOCAL_DATA_CONNECTION_MODE;
// These will be set when just before a data connection is opened
// in _openDataConnection_()
__passiveHost = null;
__passivePort = -1;
}
public boolean enterRemoteActiveMode(InetAddress host, int port)
throws IOException
{
if (FTPReply.isPositiveCompletion(port(host, port)))
{
__dataConnectionMode = ACTIVE_REMOTE_DATA_CONNECTION_MODE;
__passiveHost = null;
__passivePort = -1;
return true;
}
return false;
}
public boolean enterRemotePassiveMode() throws IOException
{
if (pasv() != FTPReply.ENTERING_PASSIVE_MODE)
return false;
__dataConnectionMode = PASSIVE_REMOTE_DATA_CONNECTION_MODE;
__parsePassiveModeReply((String)_replyLines.elementAt(0));
return true;
}
public String getPassiveHost()
{
return __passiveHost;
}
public int getPassivePort()
{
return __passivePort;
}
public int getDataConnectionMode()
{
return __dataConnectionMode;
}
public boolean setFileType(int fileType) throws IOException
{
if (FTPReply.isPositiveCompletion(type(fileType)))
{
__fileType = fileType;
__fileFormat = FTP.NON_PRINT_TEXT_FORMAT;
return true;
}
return false;
}
public boolean setFileType(int fileType, int formatOrByteSize)
throws IOException
{
if (FTPReply.isPositiveCompletion(type(fileType, formatOrByteSize)))
{
__fileType = fileType;
__fileFormat = formatOrByteSize;
return true;
}
return false;
}
public boolean setFileStructure(int structure) throws IOException
{
if (FTPReply.isPositiveCompletion(stru(structure)))
{
__fileStructure = structure;
return true;
}
return false;
}
public boolean setFileTransferMode(int mode) throws IOException
{
if (FTPReply.isPositiveCompletion(mode(mode)))
{
__fileTransferMode = mode;
return true;
}
return false;
}
public boolean remoteRetrieve(String filename) throws IOException
{
if (__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE ||
__dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE)
return FTPReply.isPositivePreliminary(retr(filename));
return false;
}
public boolean remoteStore(String filename) throws IOException
{
if (__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE ||
__dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE)
return FTPReply.isPositivePreliminary(stor(filename));
return false;
}
public boolean remoteStoreUnique(String filename) throws IOException
{
if (__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE ||
__dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE)
return FTPReply.isPositivePreliminary(stou(filename));
return false;
}
public boolean remoteStoreUnique() throws IOException
{
if (__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE ||
__dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE)
return FTPReply.isPositivePreliminary(stou());
return false;
}
public boolean remoteAppend(String filename) throws IOException
{
if (__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE ||
__dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE)
return FTPReply.isPositivePreliminary(stor(filename));
return false;
}
public boolean completePendingCommand() throws IOException
{
return FTPReply.isPositiveCompletion(getReply());
}
/***
* Retrieves a named file from the server and writes it to the given
* OutputStream. This method does NOT close the given OutputStream.
* If the current file type is ASCII, line separators in the file are
* converted to the local representation.
*
* @param remote The name of the remote file.
* @param local The local OutputStream to which to write the file.
* @return True if successfully completed, false if not.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception CopyStreamException If an I/O error occurs while actually
* transferring the file. The CopyStreamException allows you to
* determine the number of bytes transferred and the IOException
* causing the error. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending a
* command to the server or receiving a reply from the server.
***/
public boolean retrieveFile(String remote, OutputStream local)
throws IOException
{
InputStream input;
Socket socket;
if ((socket = _openDataConnection_(FTPCommand.RETR, remote)) == null)
return false;
input = new BufferedInputStream(socket.getInputStream(),
getBufferSize());
if (__fileType == ASCII_FILE_TYPE)
input = new FromNetASCIIInputStream(input);
// Treat everything else as binary for now
try
{
Util.copyStream(input, local, getBufferSize(),
CopyStreamEvent.UNKNOWN_STREAM_SIZE, null,
false);
}
catch (IOException e)
{
try
{
socket.close();
}
catch (IOException f)
{}
throw e;
}
socket.close();
return completePendingCommand();
}
public InputStream retrieveFileStream(String remote) throws IOException
{
InputStream input;
Socket socket;
if ((socket = _openDataConnection_(FTPCommand.RETR, remote)) == null)
return null;
input = socket.getInputStream();
if (__fileType == ASCII_FILE_TYPE) {
// We buffer ascii transfers because the buffering has to
// be interposed between FromNetASCIIOutputSream and the underlying
// socket input stream. We don't buffer binary transfers
// because we don't want to impose a buffering policy on the
// programmer if possible. Programmers can decide on their
// own if they want to wrap the SocketInputStream we return
// for file types other than ASCII.
input = new BufferedInputStream(input,
getBufferSize());
input = new FromNetASCIIInputStream(input);
}
return new org.apache.commons.net.io.SocketInputStream(socket, input);
}
public boolean storeFile(String remote, InputStream local)
throws IOException
{
return __storeFile(FTPCommand.STOR, remote, local);
}
public OutputStream storeFileStream(String remote) throws IOException
{
return __storeFileStream(FTPCommand.STOR, remote);
}
public boolean appendFile(String remote, InputStream local)
throws IOException
{
return __storeFile(FTPCommand.APPE, remote, local);
}
public OutputStream appendFileStream(String remote) throws IOException
{
return __storeFileStream(FTPCommand.APPE, remote);
}
public boolean storeUniqueFile(String remote, InputStream local)
throws IOException
{
return __storeFile(FTPCommand.STOU, remote, local);
}
public OutputStream storeUniqueFileStream(String remote) throws IOException
{
return __storeFileStream(FTPCommand.STOU, remote);
}
public boolean storeUniqueFile(InputStream local) throws IOException
{
return __storeFile(FTPCommand.STOU, null, local);
}
public OutputStream storeUniqueFileStream() throws IOException
{
return __storeFileStream(FTPCommand.STOU, null);
}
/***
* Reserve a number of bytes on the server for the next file transfer.
*
* @param bytes The number of bytes which the server should allocate.
* @return True if successfully completed, false if not.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending a
* command to the server or receiving a reply from the server.
***/
public boolean allocate(int bytes) throws IOException
{
return FTPReply.isPositiveCompletion(allo(bytes));
}
public boolean allocate(int bytes, int recordSize) throws IOException
{
return FTPReply.isPositiveCompletion(allo(bytes, recordSize));
}
private boolean restart(long offset) throws IOException
{
__restartOffset = 0;
return FTPReply.isPositiveIntermediate(rest(Long.toString(offset)));
}
public void setRestartOffset(long offset)
{
if (offset >= 0)
__restartOffset = offset;
}
public long getRestartOffset()
{
return __restartOffset;
}
public boolean rename(String from, String to) throws IOException
{
if (!FTPReply.isPositiveIntermediate(rnfr(from)))
return false;
return FTPReply.isPositiveCompletion(rnto(to));
}
public boolean abort() throws IOException
{
return FTPReply.isPositiveCompletion(abor());
}
public boolean deleteFile(String pathname) throws IOException
{
return FTPReply.isPositiveCompletion(dele(pathname));
}
public boolean removeDirectory(String pathname) throws IOException
{
return FTPReply.isPositiveCompletion(rmd(pathname));
}
public boolean makeDirectory(String pathname) throws IOException
{
return FTPReply.isPositiveCompletion(mkd(pathname));
}
public String printWorkingDirectory() throws IOException
{
if (pwd() != FTPReply.PATHNAME_CREATED)
return null;
return __parsePathname((String)_replyLines.elementAt(0));
}
public boolean sendSiteCommand(String arguments) throws IOException
{
return FTPReply.isPositiveCompletion(site(arguments));
}
public String getSystemName() throws IOException
{
//if (syst() == FTPReply.NAME_SYSTEM_TYPE)
// Technically, we should expect a NAME_SYSTEM_TYPE response, but
// in practice FTP servers deviate, so we soften the condition to
// a positive completion.
if (__systemName == null && FTPReply.isPositiveCompletion(syst()))
__systemName = ((String)_replyLines.elementAt(0)).substring(4);
return __systemName;
}
public String listHelp() throws IOException
{
if (FTPReply.isPositiveCompletion(help()))
return getReplyString();
return null;
}
public String listHelp(String command) throws IOException
{
if (FTPReply.isPositiveCompletion(help(command)))
return getReplyString();
return null;
}
public boolean sendNoOp() throws IOException
{
return FTPReply.isPositiveCompletion(noop());
}
public String[] listNames(String pathname) throws IOException
{
String line;
Socket socket;
BufferedReader reader;
Vector results;
if ((socket = _openDataConnection_(FTPCommand.NLST, pathname)) == null)
return null;
reader =
new BufferedReader(new InputStreamReader(socket.getInputStream(), getControlEncoding()));
results = new Vector();
while ((line = reader.readLine()) != null)
results.addElement(line);
reader.close();
socket.close();
if (completePendingCommand())
{
String[] result;
result = new String[results.size()];
results.copyInto(result);
return result;
}
return null;
}
public String[] listNames() throws IOException
{
return listNames(null);
}
public FTPFile[] listFiles(String parserKey, String pathname)
throws IOException
{
FTPListParseEngine engine =
initiateListParsing(parserKey, pathname);
return engine.getFiles();
}
public FTPFile[] listFiles(String pathname)
throws IOException
{
String key = null;
FTPListParseEngine engine =
initiateListParsing(key, pathname);
return engine.getFiles();
}
public FTPFile[] listFiles()
throws IOException
{
return listFiles((String) null);
}
public FTPListParseEngine initiateListParsing()
throws IOException
{
return initiateListParsing((String) null);
}
public FTPListParseEngine initiateListParsing(
String pathname)
throws IOException
{
String key = null;
return initiateListParsing(key, pathname);
}
public FTPListParseEngine initiateListParsing(
String parserKey, String pathname)
throws IOException
{
// We cache the value to avoid creation of a new object every
// time a file listing is generated.
if(__entryParser == null) {
if (null != parserKey) {
// if a parser key was supplied in the parameters,
// use that to create the paraser
__entryParser =
__parserFactory.createFileEntryParser(parserKey);
} else {
// if no parserKey was supplied, check for a configuration
// in the params, and if non-null, use that.
if (null != __configuration) {
__entryParser =
__parserFactory.createFileEntryParser(__configuration);
} else {
// if a parserKey hasn't been supplied, and a configuration
// hasn't been supplied, then autodetect by calling
// the SYST command and use that to choose the parser.
__entryParser =
__parserFactory.createFileEntryParser(getSystemName());
}
}
}
return initiateListParsing(__entryParser, pathname);
}
private FTPListParseEngine initiateListParsing(
FTPFileEntryParser parser, String pathname)
throws IOException
{
Socket socket;
FTPListParseEngine engine = new FTPListParseEngine(parser);
if ((socket = _openDataConnection_(FTPCommand.LIST, pathname)) == null)
{
return engine;
}
engine.readServerList(socket.getInputStream(), getControlEncoding());
socket.close();
completePendingCommand();
return engine;
}
public String getStatus() throws IOException
{
if (FTPReply.isPositiveCompletion(stat()))
return getReplyString();
return null;
}
public String getStatus(String pathname) throws IOException
{
if (FTPReply.isPositiveCompletion(stat(pathname)))
return getReplyString();
return null;
}
public FTPFile[] listFiles(FTPFileListParser parser, String pathname)
throws IOException
{
Socket socket;
FTPFile[] results;
if ((socket = _openDataConnection_(FTPCommand.LIST, pathname)) == null)
return new FTPFile[0];
results = parser.parseFileList(socket.getInputStream(), getControlEncoding());
socket.close();
completePendingCommand();
return results;
}
public FTPFile[] listFiles(FTPFileListParser parser) throws IOException
{
return listFiles(parser, null);
}
public FTPFileList createFileList(FTPFileEntryParser parser) throws IOException
{
return createFileList(null, parser);
}
public FTPFileList createFileList(String pathname,
FTPFileEntryParser parser)
throws IOException
{
Socket socket;
if ((socket = _openDataConnection_(FTPCommand.LIST, pathname)) == null)
{
return null;
}
FTPFileList list = FTPFileList.create(socket.getInputStream(), parser);
socket.close();
completePendingCommand();
return list;
}
/**
* Set the internal buffer size.
*
* @param bufSize The size of the buffer
*/
public void setBufferSize(int bufSize) {
__bufferSize = bufSize;
}
/**
* Retrieve the current internal buffer size.
* @return The current buffer size.
*/
public int getBufferSize() {
return __bufferSize;
}
public void configure(FTPClientConfig config) {
this.__configuration = config;
}
}
package com.ideal.crm.star.utils;
public final class FTPCommand
{
public static final int USER = 0;
public static final int PASS = 1;
public static final int ACCT = 2;
public static final int CWD = 3;
public static final int CDUP = 4;
public static final int SMNT = 5;
public static final int REIN = 6;
public static final int QUIT = 7;
public static final int PORT = 8;
public static final int PASV = 9;
public static final int TYPE = 10;
public static final int STRU = 11;
public static final int MODE = 12;
public static final int RETR = 13;
public static final int STOR = 14;
public static final int STOU = 15;
public static final int APPE = 16;
public static final int ALLO = 17;
public static final int REST = 18;
public static final int RNFR = 19;
public static final int RNTO = 20;
public static final int ABOR = 21;
public static final int DELE = 22;
public static final int RMD = 23;
public static final int MKD = 24;
public static final int PWD = 25;
public static final int LIST = 26;
public static final int NLST = 27;
public static final int SITE = 28;
public static final int SYST = 29;
public static final int STAT = 30;
public static final int HELP = 31;
public static final int NOOP = 32;
public static final int USERNAME = USER;
public static final int PASSWORD = PASS;
public static final int ACCOUNT = ACCT;
public static final int CHANGE_WORKING_DIRECTORY = CWD;
public static final int CHANGE_TO_PARENT_DIRECTORY = CDUP;
public static final int STRUCTURE_MOUNT = SMNT;
public static final int REINITIALIZE = REIN;
public static final int LOGOUT = QUIT;
public static final int DATA_PORT = PORT;
public static final int PASSIVE = PASV;
public static final int REPRESENTATION_TYPE = TYPE;
public static final int FILE_STRUCTURE = STRU;
public static final int TRANSFER_MODE = MODE;
public staticpackage com.ideal.crm.star.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Vector;
import org.apache.commons.net.MalformedServerReplyException;
import org.apache.commons.net.ProtocolCommandListener;
import org.apache.commons.net.ProtocolCommandSupport;
import org.apache.commons.net.SocketClient;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.telnet.TelnetClient;
public class FTP extends TelnetClient
{
/*** The default FTP data port (20). ***/
public static final int DEFAULT_DATA_PORT = 20;
/*** The default FTP control port (21). ***/
public static final int DEFAULT_PORT = 21;
public static final int ASCII_FILE_TYPE = 0;
public static final int EBCDIC_FILE_TYPE = 1;
public static final int IMAGE_FILE_TYPE = 2;
public static final int BINARY_FILE_TYPE = 2;
public static final int LOCAL_FILE_TYPE = 3;
public static final int NON_PRINT_TEXT_FORMAT = 4;
public static final int TELNET_TEXT_FORMAT = 5;
public static final int CARRIAGE_CONTROL_TEXT_FORMAT = 6;
public static final int FILE_STRUCTURE = 7;
public static final int RECORD_STRUCTURE = 8;
public static final int PAGE_STRUCTURE = 9;
public static final int STREAM_TRANSFER_MODE = 10;
public static final int BLOCK_TRANSFER_MODE = 11;
public static final int COMPRESSED_TRANSFER_MODE = 12;
// We have to ensure that the protocol communication is in ASCII
// but we use ISO-8859-1 just in case 8-bit characters cross
// the wire.
/**
* The default character encoding used for communicating over an
* FTP control connection. The default encoding is an
* ASCII-compatible encoding. Some FTP servers expect other
* encodings. You can change the encoding used by an FTP instance
* with {@link #setControlEncoding setControlEncoding}.
*/
public static final String DEFAULT_CONTROL_ENCODING = "ISO-8859-1";
private static final String __modes = "ABILNTCFRPSBC";
private StringBuffer __commandBuffer;
BufferedReader _controlInput;
BufferedWriter _controlOutput;
int _replyCode;
Vector _replyLines;
boolean _newReplyString;
String _replyString;
String _controlEncoding;
/***
* A ProtocolCommandSupport object used to manage the registering of
* ProtocolCommandListeners and te firing of ProtocolCommandEvents.
***/
protected ProtocolCommandSupport _commandSupport_;
/***
* The default FTP constructor. Sets the default port to
* DEFAULT_PORT
and initializes internal data structures
* for saving FTP reply information.
***/
public FTP()
{
setDefaultPort(DEFAULT_PORT);
__commandBuffer = new StringBuffer();
_replyLines = new Vector();
_newReplyString = false;
_replyString = null;
_commandSupport_ = new ProtocolCommandSupport(this);
_controlEncoding = DEFAULT_CONTROL_ENCODING;
}
private void __getReply() throws IOException
{
int length;
_newReplyString = true;
_replyLines.setSize(0);
String line = _controlInput.readLine();
if (line == null)
throw new FTPConnectionClosedException(
"Connection closed without indication.");
// In case we run into an anomaly we don't want fatal index exceptions
// to be thrown.
length = line.length();
if (length < 3)
throw new MalformedServerReplyException(
"Truncated server reply: " + line);
try
{
String code = line.substring(0, 3);
_replyCode = Integer.parseInt(code);
}
catch (NumberFormatException e)
{
throw new MalformedServerReplyException(
"Could not parse response code.\nServer Reply: " + line);
}
_replyLines.addElement(line);
// Get extra lines if message continues.
if (length > 3 && line.charAt(3) == '-')
{
do
{
line = _controlInput.readLine();
if (line == null)
throw new FTPConnectionClosedException(
"Connection closed without indication.");
_replyLines.addElement(line);
// The length() check handles problems that could arise from readLine()
// returning too soon after encountering a naked CR or some other
// anomaly.
}
while (!(line.length() >= 4 && line.charAt(3) != '-' &&
Character.isDigit(line.charAt(0))));
// This is too strong a condition because of non-conforming ftp
// servers like ftp.funet.fi which sent 226 as the last line of a
// 426 multi-line reply in response to ls /. We relax the condition to
// test that the line starts with a digit rather than starting with
// the code.
// line.startsWith(code)));
}
if (_commandSupport_.getListenerCount() > 0)
_commandSupport_.fireReplyReceived(_replyCode, getReplyString());
if (_replyCode == FTPReply.SERVICE_NOT_AVAILABLE)
throw new FTPConnectionClosedException(
"FTP response 421 received. Server closed connection.");
}
// initiates control connections and gets initial reply
protected void _connectAction_() throws IOException
{
super._connectAction_();
_controlInput =
new BufferedReader(new InputStreamReader(getInputStream(),
getControlEncoding()));
_controlOutput =
new BufferedWriter(new OutputStreamWriter(getOutputStream(),
getControlEncoding()));
__getReply();
// If we received code 120, we have to fetch completion reply.
if (FTPReply.isPositivePreliminary(_replyCode))
__getReply();
}
/**
* Sets the character encoding used by the FTP control connection.
* Some FTP servers require that commands be issued in a non-ASCII
* encoding like UTF-8 so that filenames with multi-byte character
* representations (e.g, Big 8) can be specified.
*
* @param encoding The new character encoding for the control connection.
*/
public void setControlEncoding(String encoding) {
_controlEncoding = encoding;
}
/**
* @return The character encoding used to communicate over the
* control connection.
*/
public String getControlEncoding() {
return _controlEncoding;
}
/***
* Adds a ProtocolCommandListener. Delegates this task to
* {@link #_commandSupport_ _commandSupport_ }.
*
* @param listener The ProtocolCommandListener to add.
***/
public void addProtocolCommandListener(ProtocolCommandListener listener)
{
_commandSupport_.addProtocolCommandListener(listener);
}
/***
* Removes a ProtocolCommandListener. Delegates this task to
* {@link #_commandSupport_ _commandSupport_ }.
*
* @param listener The ProtocolCommandListener to remove.
***/
public void removeProtocolCommandListener(ProtocolCommandListener listener)
{
_commandSupport_.removeProtocolCommandListener(listener);
}
/***
* Closes the control connection to the FTP server and sets to null
* some internal data so that the memory may be reclaimed by the
* garbage collector. The reply text and code information from the
* last command is voided so that the memory it used may be reclaimed.
*
* @exception IOException If an error occurs while disconnecting.
***/
public void disconnect() throws IOException
{
super.disconnect();
_controlInput = null;
_controlOutput = null;
_replyLines.setSize(0);
_newReplyString = false;
_replyString = null;
}
/***
* Sends an FTP command to the server, waits for a reply and returns the
* numerical response code. After invocation, for more detailed
* information, the actual reply text can be accessed by calling
* {@link #getReplyString getReplyString } or
* {@link #getReplyStrings getReplyStrings }.
*
* @param command The text representation of the FTP command to send.
* @param args The arguments to the FTP command. If this parameter is
* set to null, then the command is sent with no argument.
* @return The integer value of the FTP reply code returned by the server
* in response to the command.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int sendCommand(String command, String args) throws IOException
{
String message;
__commandBuffer.setLength(0);
__commandBuffer.append(command);
if (args != null)
{
__commandBuffer.append(' ');
__commandBuffer.append(args);
}
__commandBuffer.append(SocketClient.NETASCII_EOL);
try{
_controlOutput.write(message = __commandBuffer.toString());
_controlOutput.flush();
}
catch (SocketException e)
{
if (!isConnected() || !socketIsConnected(_socket_))
{
throw new FTPConnectionClosedException("Connection unexpectedly closed.");
}
else
{
throw e;
}
}
if (_commandSupport_.getListenerCount() > 0)
_commandSupport_.fireCommandSent(command, message);
__getReply();
return _replyCode;
}
/**
* Checks if the socket is connected using reflection to be backward compatible.
* The return value of this method is only meaningful in an java 1.4 environment.
*
* @param socket
* @return true if connected or pre java 1.4
*/
private boolean socketIsConnected(Socket socket)
{
if (socket == null)
{
return false;
}
try
{
Method isConnected = socket.getClass().getMethod("isConnected", null);
return ((Boolean) isConnected.invoke(socket, null)).booleanValue();
}
catch (NoSuchMethodException e)
{
return true;
}
catch (IllegalAccessException e)
{
return true;
}
catch (InvocationTargetException e)
{
return true;
}
}
/***
* Sends an FTP command to the server, waits for a reply and returns the
* numerical response code. After invocation, for more detailed
* information, the actual reply text can be accessed by calling
* {@link #getReplyString getReplyString } or
* {@link #getReplyStrings getReplyStrings }.
*
* @param command The FTPCommand constant corresponding to the FTP command
* to send.
* @param args The arguments to the FTP command. If this parameter is
* set to null, then the command is sent with no argument.
* @return The integer value of the FTP reply code returned by the server
* in response to the command.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int sendCommand(int command, String args) throws IOException
{
return sendCommand(FTPCommand._commands[command], args);
}
/***
* Sends an FTP command with no arguments to the server, waits for a
* reply and returns the numerical response code. After invocation, for
* more detailed information, the actual reply text can be accessed by
* calling {@link #getReplyString getReplyString } or
* {@link #getReplyStrings getReplyStrings }.
*
* @param command The text representation of the FTP command to send.
* @return The integer value of the FTP reply code returned by the server
* in response to the command.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int sendCommand(String command) throws IOException
{
return sendCommand(command, null);
}
/***
* Sends an FTP command with no arguments to the server, waits for a
* reply and returns the numerical response code. After invocation, for
* more detailed information, the actual reply text can be accessed by
* calling {@link #getReplyString getReplyString } or
* {@link #getReplyStrings getReplyStrings }.
*
* @param command The FTPCommand constant corresponding to the FTP command
* to send.
* @return The integer value of the FTP reply code returned by the server
* in response to the command.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int sendCommand(int command) throws IOException
{
return sendCommand(command, null);
}
/***
* Returns the integer value of the reply code of the last FTP reply.
* You will usually only use this method after you connect to the
* FTP server to check that the connection was successful since
* connect
is of type void.
*
* @return The integer value of the reply code of the last FTP reply.
***/
public int getReplyCode()
{
return _replyCode;
}
/***
* Fetches a reply from the FTP server and returns the integer reply
* code. After calling this method, the actual reply text can be accessed
* from either calling {@link #getReplyString getReplyString } or
* {@link #getReplyStrings getReplyStrings }. Only use this
* method if you are implementing your own FTP client or if you need to
* fetch a secondary response from the FTP server.
*
* @return The integer value of the reply code of the fetched FTP reply.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while receiving the
* server reply.
***/
public int getReply() throws IOException
{
__getReply();
return _replyCode;
}
/***
* Returns the lines of text from the last FTP server response as an array
* of strings, one entry per line. The end of line markers of each are
* stripped from each line.
*
* @return The lines of text from the last FTP response as an array.
***/
public String[] getReplyStrings()
{
String[] lines;
lines = new String[_replyLines.size()];
_replyLines.copyInto(lines);
return lines;
}
/***
* Returns the entire text of the last FTP server response exactly
* as it was received, including all end of line markers in NETASCII
* format.
*
* @return The entire text from the last FTP response as a String.
***/
public String getReplyString()
{
Enumeration en;
StringBuffer buffer;
if (!_newReplyString)
return _replyString;
buffer = new StringBuffer(256);
en = _replyLines.elements();
while (en.hasMoreElements())
{
buffer.append((String)en.nextElement());
buffer.append(SocketClient.NETASCII_EOL);
}
_newReplyString = false;
return (_replyString = buffer.toString());
}
/***
* A convenience method to send the FTP USER command to the server,
* receive the reply, and return the reply code.
*
* @param username The username to login under.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int user(String username) throws IOException
{
return sendCommand(FTPCommand.USER, username);
}
/**
* A convenience method to send the FTP PASS command to the server,
* receive the reply, and return the reply code.
* @param password The plain text password of the username being logged into.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
*/
public int pass(String password) throws IOException
{
return sendCommand(FTPCommand.PASS, password);
}
/***
* A convenience method to send the FTP ACCT command to the server,
* receive the reply, and return the reply code.
*
* @param account The account name to access.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int acct(String account) throws IOException
{
return sendCommand(FTPCommand.ACCT, account);
}
/***
* A convenience method to send the FTP ABOR command to the server,
* receive the reply, and return the reply code.
*
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int abor() throws IOException
{
return sendCommand(FTPCommand.ABOR);
}
/***
* A convenience method to send the FTP CWD command to the server,
* receive the reply, and return the reply code.
*
* @param directory The new working directory.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int cwd(String directory) throws IOException
{
return sendCommand(FTPCommand.CWD, directory);
}
/***
* A convenience method to send the FTP CDUP command to the server,
* receive the reply, and return the reply code.
*
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int cdup() throws IOException
{
return sendCommand(FTPCommand.CDUP);
}
/***
* A convenience method to send the FTP QUIT command to the server,
* receive the reply, and return the reply code.
*
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int quit() throws IOException
{
return sendCommand(FTPCommand.QUIT);
}
/***
* A convenience method to send the FTP REIN command to the server,
* receive the reply, and return the reply code.
*
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int rein() throws IOException
{
return sendCommand(FTPCommand.REIN);
}
/***
* A convenience method to send the FTP SMNT command to the server,
* receive the reply, and return the reply code.
*
* @param dir The directory name.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int smnt(String dir) throws IOException
{
return sendCommand(FTPCommand.SMNT, dir);
}
/***
* A convenience method to send the FTP PORT command to the server,
* receive the reply, and return the reply code.
*
* @param host The host owning the port.
* @param port The new port.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int port(InetAddress host, int port) throws IOException
{
int num;
StringBuffer info = new StringBuffer(24);
info.append(host.getHostAddress().replace('.', ','));
num = port >>> 8;
info.append(',');
info.append(num);
info.append(',');
num = port & 0xff;
info.append(num);
return sendCommand(FTPCommand.PORT, info.toString());
}
/***
* A convenience method to send the FTP PASV command to the server,
* receive the reply, and return the reply code. Remember, it's up
* to you to interpret the reply string containing the host/port
* information.
*
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int pasv() throws IOException
{
return sendCommand(FTPCommand.PASV);
}
/**
* A convenience method to send the FTP TYPE command for text files
* to the server, receive the reply, and return the reply code.
* @param fileType The type of the file (one of the FILE_TYPE
* constants).
* @param formatOrByteSize The format of the file (one of the
* _FORMAT
constants. In the case of
* LOCAL_FILE_TYPE
, the byte size.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
*/
public int type(int fileType, int formatOrByteSize) throws IOException
{
StringBuffer arg = new StringBuffer();
arg.append(__modes.charAt(fileType));
arg.append(' ');
if (fileType == LOCAL_FILE_TYPE)
arg.append(formatOrByteSize);
else
arg.append(__modes.charAt(formatOrByteSize));
return sendCommand(FTPCommand.TYPE, arg.toString());
}
/**
* A convenience method to send the FTP TYPE command to the server,
* receive the reply, and return the reply code.
*
* @param fileType The type of the file (one of the FILE_TYPE
* constants).
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
*/
public int type(int fileType) throws IOException
{
return sendCommand(FTPCommand.TYPE,
__modes.substring(fileType, fileType + 1));
}
/***
* A convenience method to send the FTP STRU command to the server,
* receive the reply, and return the reply code.
*
* @param structure The structure of the file (one of the
* _STRUCTURE
constants).
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int stru(int structure) throws IOException
{
return sendCommand(FTPCommand.STRU,
__modes.substring(structure, structure + 1));
}
/***
* A convenience method to send the FTP MODE command to the server,
* receive the reply, and return the reply code.
*
* @param mode The transfer mode to use (one of the
* TRANSFER_MODE
constants).
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int mode(int mode) throws IOException
{
return sendCommand(FTPCommand.MODE,
__modes.substring(mode, mode + 1));
}
/***
* A convenience method to send the FTP RETR command to the server,
* receive the reply, and return the reply code. Remember, it is up
* to you to manage the data connection. If you don't need this low
* level of access, use {@link org.apache.commons.net.ftp.FTPClient}
* , which will handle all low level details for you.
*
* @param pathname The pathname of the file to retrieve.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int retr(String pathname) throws IOException
{
return sendCommand(FTPCommand.RETR, pathname);
}
/***
* A convenience method to send the FTP STOR command to the server,
* receive the reply, and return the reply code. Remember, it is up
* to you to manage the data connection. If you don't need this low
* level of access, use {@link org.apache.commons.net.ftp.FTPClient}
* , which will handle all low level details for you.
*
* @param pathname The pathname to use for the file when stored at
* the remote end of the transfer.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int stor(String pathname) throws IOException
{
return sendCommand(FTPCommand.STOR, pathname);
}
/***
* A convenience method to send the FTP STOU command to the server,
* receive the reply, and return the reply code. Remember, it is up
* to you to manage the data connection. If you don't need this low
* level of access, use {@link org.apache.commons.net.ftp.FTPClient}
* , which will handle all low level details for you.
*
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int stou() throws IOException
{
return sendCommand(FTPCommand.STOU);
}
/***
* A convenience method to send the FTP STOU command to the server,
* receive the reply, and return the reply code. Remember, it is up
* to you to manage the data connection. If you don't need this low
* level of access, use {@link org.apache.commons.net.ftp.FTPClient}
* , which will handle all low level details for you.
* @param pathname The base pathname to use for the file when stored at
* the remote end of the transfer. Some FTP servers
* require this.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
*/
public int stou(String pathname) throws IOException
{
return sendCommand(FTPCommand.STOU, pathname);
}
/***
* A convenience method to send the FTP APPE command to the server,
* receive the reply, and return the reply code. Remember, it is up
* to you to manage the data connection. If you don't need this low
* level of access, use {@link org.apache.commons.net.ftp.FTPClient}
* , which will handle all low level details for you.
*
* @param pathname The pathname to use for the file when stored at
* the remote end of the transfer.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int appe(String pathname) throws IOException
{
return sendCommand(FTPCommand.APPE, pathname);
}
/***
* A convenience method to send the FTP ALLO command to the server,
* receive the reply, and return the reply code.
*
* @param bytes The number of bytes to allocate.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int allo(int bytes) throws IOException
{
return sendCommand(FTPCommand.ALLO, Integer.toString(bytes));
}
/***
* A convenience method to send the FTP ALLO command to the server,
* receive the reply, and return the reply code.
*
* @param bytes The number of bytes to allocate.
* @param recordSize The size of a record.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int allo(int bytes, int recordSize) throws IOException
{
return sendCommand(FTPCommand.ALLO, Integer.toString(bytes) + " R " +
Integer.toString(recordSize));
}
/***
* A convenience method to send the FTP REST command to the server,
* receive the reply, and return the reply code.
*
* @param marker The marker at which to restart a transfer.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int rest(String marker) throws IOException
{
return sendCommand(FTPCommand.REST, marker);
}
/***
* A convenience method to send the FTP RNFR command to the server,
* receive the reply, and return the reply code.
*
* @param pathname The pathname to rename from.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int rnfr(String pathname) throws IOException
{
return sendCommand(FTPCommand.RNFR, pathname);
}
/***
* A convenience method to send the FTP RNTO command to the server,
* receive the reply, and return the reply code.
*
* @param pathname The pathname to rename to
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int rnto(String pathname) throws IOException
{
return sendCommand(FTPCommand.RNTO, pathname);
}
/***
* A convenience method to send the FTP DELE command to the server,
* receive the reply, and return the reply code.
*
* @param pathname The pathname to delete.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int dele(String pathname) throws IOException
{
return sendCommand(FTPCommand.DELE, pathname);
}
/***
* A convenience method to send the FTP RMD command to the server,
* receive the reply, and return the reply code.
*
* @param pathname The pathname of the directory to remove.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int rmd(String pathname) throws IOException
{
return sendCommand(FTPCommand.RMD, pathname);
}
/***
* A convenience method to send the FTP MKD command to the server,
* receive the reply, and return the reply code.
*
* @param pathname The pathname of the new directory to create.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int mkd(String pathname) throws IOException
{
return sendCommand(FTPCommand.MKD, pathname);
}
/***
* A convenience method to send the FTP PWD command to the server,
* receive the reply, and return the reply code.
*
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int pwd() throws IOException
{
return sendCommand(FTPCommand.PWD);
}
/***
* A convenience method to send the FTP LIST command to the server,
* receive the reply, and return the reply code. Remember, it is up
* to you to manage the data connection. If you don't need this low
* level of access, use {@link org.apache.commons.net.ftp.FTPClient}
* , which will handle all low level details for you.
*
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int list() throws IOException
{
return sendCommand(FTPCommand.LIST);
}
/***
* A convenience method to send the FTP LIST command to the server,
* receive the reply, and return the reply code. Remember, it is up
* to you to manage the data connection. If you don't need this low
* level of access, use {@link org.apache.commons.net.ftp.FTPClient}
* , which will handle all low level details for you.
*
* @param pathname The pathname to list.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int list(String pathname) throws IOException
{
return sendCommand(FTPCommand.LIST, pathname);
}
/***
* A convenience method to send the FTP NLST command to the server,
* receive the reply, and return the reply code. Remember, it is up
* to you to manage the data connection. If you don't need this low
* level of access, use {@link org.apache.commons.net.ftp.FTPClient}
* , which will handle all low level details for you.
*
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int nlst() throws IOException
{
return sendCommand(FTPCommand.NLST);
}
/***
* A convenience method to send the FTP NLST command to the server,
* receive the reply, and return the reply code. Remember, it is up
* to you to manage the data connection. If you don't need this low
* level of access, use {@link org.apache.commons.net.ftp.FTPClient}
* , which will handle all low level details for you.
*
* @param pathname The pathname to list.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int nlst(String pathname) throws IOException
{
return sendCommand(FTPCommand.NLST, pathname);
}
/***
* A convenience method to send the FTP SITE command to the server,
* receive the reply, and return the reply code.
*
* @param parameters The site parameters to send.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int site(String parameters) throws IOException
{
return sendCommand(FTPCommand.SITE, parameters);
}
/***
* A convenience method to send the FTP SYST command to the server,
* receive the reply, and return the reply code.
*
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int syst() throws IOException
{
return sendCommand(FTPCommand.SYST);
}
/***
* A convenience method to send the FTP STAT command to the server,
* receive the reply, and return the reply code.
*
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int stat() throws IOException
{
return sendCommand(FTPCommand.STAT);
}
/***
* A convenience method to send the FTP STAT command to the server,
* receive the reply, and return the reply code.
*
* @param pathname A pathname to list.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int stat(String pathname) throws IOException
{
return sendCommand(FTPCommand.STAT, pathname);
}
/***
* A convenience method to send the FTP HELP command to the server,
* receive the reply, and return the reply code.
*
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int help() throws IOException
{
return sendCommand(FTPCommand.HELP);
}
/***
* A convenience method to send the FTP HELP command to the server,
* receive the reply, and return the reply code.
*
* @param command The command name on which to request help.
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int help(String command) throws IOException
{
return sendCommand(FTPCommand.HELP, command);
}
/***
* A convenience method to send the FTP NOOP command to the server,
* receive the reply, and return the reply code.
*
* @return The reply code received from the server.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a result
* of the client being idle or some other reason causing the server
* to send FTP reply code 421. This exception may be caught either
* as an IOException or independently as itself.
* @exception IOException If an I/O error occurs while either sending the
* command or receiving the server reply.
***/
public int noop() throws IOException
{
return sendCommand(FTPCommand.NOOP);
}
}
/* Emacs configuration
* Local variables: **
* mode: java **
* c-basic-offset: 4 **
* indent-tabs-mode: nil **
* End: **
*/
package com.ideal.crm.star.ftp;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.ideal.crm.common.exception.FTPClientException;
import com.ideal.crm.star.utils.CustFTPUtils;
public class TestFileRead {
public static void readBigFile() throws FTPClientException{
CustFTPUtils custFTPUtils = CustFTPUtils.getInstance();
InputStream ins = custFTPUtils.get("/ftpdata/offer/eda_out/out_1124/ODS_TO_CRM_XJPD_201604.TXT", true);
// 读取配置文件为输入流
InputStreamReader inputStreamReader = new InputStreamReader(ins); // ir
// 接收从键盘得到的字符
BufferedReader in = new BufferedReader(inputStreamReader); // 对IR进行包装
//
// File file=new File("E:\\ftpdata\\offer\\eda_out\\out_1124\\ODS_TO_CRM_XJPD_201604.TXT");
// FileInputStream infs=null;
try {
//infs=new FileInputStream(file);
//InputStreamReader inputStreamReader = new InputStreamReader(infs); // ir
// 接收从键盘得到的字符
//BufferedReader in = new BufferedReader(inputStreamReader); // 对IR进行包装
String oneLine;
int i=0;
while ((oneLine = in.readLine()) != null) {
String[] strArr = oneLine.split("\\|");
i++;
System.out.println(strArr);
System.out.println(i);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
custFTPUtils.disconnect();
}
}
public static void main(String[] args){
try {
TestFileRead.readBigFile();
} catch (FTPClientException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}