本文整理汇总了Java中org.apache.commons.net.ftp.FTPClient.getReplyCode方法的典型用法代码示例。如果您正苦于以下问题:Java FTPClient.getReplyCode方法的具体用法?Java FTPClient.getReplyCode怎么用?Java FTPClient.getReplyCode使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.commons.net.ftp.FTPClient
的用法示例。
在下文中一共展示了FTPClient.getReplyCode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testFTPConnect
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
* Simple test that connects to the inbuilt ftp server and logs on
*
* @throws Exception
*/
public void testFTPConnect() throws Exception
{
logger.debug("Start testFTPConnect");
FTPClient ftp = connectClient();
try
{
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
fail("FTP server refused connection.");
}
boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN);
assertTrue("admin login not successful", login);
}
finally
{
ftp.disconnect();
}
}
示例2: uploadFile
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
* Upload a single file to FTP server with the provided FTP client object.
*
* @param sourceFilePath
* @param targetFilePath
* @param logPrefix
* @throws IOException
*/
protected void uploadFile(final FTPClient ftpClient, final String sourceFilePath, final String targetFilePath,
final String logPrefix) throws IOException {
log.info(String.format(UPLOAD_FILE, logPrefix, sourceFilePath, targetFilePath));
final File sourceFile = new File(sourceFilePath);
try (final InputStream is = new FileInputStream(sourceFile)) {
ftpClient.changeWorkingDirectory(targetFilePath);
ftpClient.storeFile(sourceFile.getName(), is);
final int replyCode = ftpClient.getReplyCode();
final String replyMessage = ftpClient.getReplyString();
if (isCommandFailed(replyCode)) {
log.error(String.format(UPLOAD_FILE_REPLY, logPrefix, replyMessage));
throw new IOException("Failed to upload file: " + sourceFilePath);
} else {
log.info(String.format(UPLOAD_FILE_REPLY, logPrefix, replyMessage));
}
}
}
示例3: makeRemoteDir
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
protected void makeRemoteDir(FTPClient ftp, String dir)
throws IOException {
String workingDirectory = ftp.printWorkingDirectory();
if (dir.indexOf("/") == 0) {
ftp.changeWorkingDirectory("/");
}
String subdir;
StringTokenizer st = new StringTokenizer(dir, "/");
while (st.hasMoreTokens()) {
subdir = st.nextToken();
if (!(ftp.changeWorkingDirectory(subdir))) {
if (!(ftp.makeDirectory(subdir))) {
int rc = ftp.getReplyCode();
if (rc != 550 && rc != 553 && rc != 521) {
throw new IOException("could not create directory: " + ftp.getReplyString());
}
} else {
ftp.changeWorkingDirectory(subdir);
}
}
}
if (workingDirectory != null) {
ftp.changeWorkingDirectory(workingDirectory);
}
}
示例4: initFtpClient
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
private FTPClient initFtpClient(String remoteDir) throws IOException {
FTPClient ftp = new FTPClient();
// 设置连接超时时间
ftp.setConnectTimeout(CONNECT_TIMEOUT);
// 设置传输文件名编码方式
ftp.setControlEncoding(CONTROL_ENCODING);
ftp.connect(host, ftpPort);
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
logger.debug("无法连接FTP");
return null;
}
boolean loginRet = ftp.login(ftpUsername, ftpPassword);
if (!loginRet) {
logger.debug("FTP登录失败");
return null;
}
// 进入被动模式
ftp.enterLocalPassiveMode();
boolean changeDirResult = MKDAndCWD(ftp, remoteDir);
if (!changeDirResult) {
logger.debug("创建/切换文件夹失败");
return null;
}
// 传输二进制文件
ftp.setFileType(FTP.BINARY_FILE_TYPE);
return ftp;
}
示例5: connectFTPServer
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
* 连接FTP服务器
*
* @author wangwei
*/
public FTPClient connectFTPServer() throws Exception {
ftpClient = new FTPClient();
try {
ftpClient.configure(getFTPClientConfig());
ftpClient.connect(ftpConstant.getHost(), ftpConstant.getPort());
ftpClient.login(ftpConstant.getUsername(), ftpConstant.getPassword());
// 设置以二进制方式传输
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// 设置被动模式
ftpClient.enterLocalPassiveMode();
ftpClient.setControlEncoding("GBK");
// 响应信息
int replyCode = ftpClient.getReplyCode();
if ((!FTPReply.isPositiveCompletion(replyCode))) {
// 关闭Ftp连接
closeFTPClient();
// 释放空间
ftpClient = null;
throw new Exception("登录FTP服务器失败,请检查!");
} else {
return ftpClient;
}
} catch (Exception e) {
ftpClient.disconnect();
ftpClient = null;
throw e;
}
}
示例6: downloadFile
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
public static boolean downloadFile(String url, int port, String username, String password,
String remotePath, String fileName, String localPath) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(url, port);
ftp.login(username, password);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(remotePath);
FTPFile[] fs = ftp.listFiles();
System.out.println(fs.length);
for (FTPFile ff : fs) {
System.out.println(ff.getName());
if (ff.getName().equals(fileName)) {
File localFile = new File(localPath + "/" + ff.getName());
OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
is.close();
}
}
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
示例7: getFTPClient
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
protected FTPClient getFTPClient() {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.setConnectTimeout(connectTimeout);
ftpClient.connect(hostname);
ftpClient.login(userName, passWord);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
FtpUtils.disconnect(ftpClient);
log.warn("FTP登陆失败,账号或者密码有误");
} else {
ftpClient.setSoTimeout(soTimeout);
/* 设置缓冲区大小 */
ftpClient.setBufferSize(bufferSize);
/* 设置服务器编码 */
ftpClient.setControlEncoding(encoding);
/* 设置以二进制方式传输 */
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
/* 设置服务器目录 */
// ftpClient.changeWorkingDirectory(directory);
ftpClient.enterLocalPassiveMode();
log.debug("成功连接并登录FTP服务器。。。");
}
} catch (Exception e) {
FtpUtils.disconnect(ftpClient);
log.error("error", e);
}
return ftpClient;
}
示例8: testFTPConnectNegative
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
* Simple negative test that connects to the inbuilt ftp server and attempts to
* log on with the wrong password.
*
* @throws Exception
*/
public void testFTPConnectNegative() throws Exception
{
logger.debug("Start testFTPConnectNegative");
FTPClient ftp = connectClient();
try
{
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
fail("FTP server refused connection.");
}
boolean login = ftp.login(USER_ADMIN, "garbage");
assertFalse("admin login successful", login);
// now attempt to list the files and check that the command does not
// succeed
FTPFile[] files = ftp.listFiles();
assertNotNull(files);
assertTrue(files.length == 0);
reply = ftp.getReplyCode();
assertTrue(FTPReply.isNegativePermanent(reply));
}
finally
{
ftp.disconnect();
}
}
示例9: uploadFile
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
* Description: 向FTP服务器上传文件
* @param url FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
* @param path FTP服务器保存目录
* @param filename 上传到FTP服务器上的文件名
* @param input 输入流
* @return 成功返回true,否则返回false
*/
public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(url, port);//连接FTP服务器
//如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(username, password);//登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
//设置FTP以2进制传输
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
//TODO 读取文件配置判断是否使用主动
ftp.enterLocalPassiveMode();//被动
//ftp.enterLocalActiveMode();//主动
//创建目录
mkDir(path,ftp);
//改变目录
ftp.changeWorkingDirectory(path);
ftp.storeFile(filename, input);
input.close();
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
示例10: create
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
* A stream obtained via this call must be closed before using other APIs of
* this class or else the invocation will block.
*/
@Override
public FSDataOutputStream create(Path file, FsPermission permission,
boolean overwrite, int bufferSize, short replication, long blockSize,
Progressable progress) throws IOException {
final FTPClient client = connect();
Path workDir = new Path(client.printWorkingDirectory());
Path absolute = makeAbsolute(workDir, file);
FileStatus status;
try {
status = getFileStatus(client, file);
} catch (FileNotFoundException fnfe) {
status = null;
}
if (status != null) {
if (overwrite && !status.isDirectory()) {
delete(client, file, false);
} else {
disconnect(client);
throw new FileAlreadyExistsException("File already exists: " + file);
}
}
Path parent = absolute.getParent();
if (parent == null || !mkdirs(client, parent, FsPermission.getDirDefault())) {
parent = (parent == null) ? new Path("/") : parent;
disconnect(client);
throw new IOException("create(): Mkdirs failed to create: " + parent);
}
client.allocate(bufferSize);
// Change to parent directory on the server. Only then can we write to the
// file on the server by opening up an OutputStream. As a side effect the
// working directory on the server is changed to the parent directory of the
// file. The FTP client connection is closed when close() is called on the
// FSDataOutputStream.
client.changeWorkingDirectory(parent.toUri().getPath());
FSDataOutputStream fos = new FSDataOutputStream(client.storeFileStream(file
.getName()), statistics) {
@Override
public void close() throws IOException {
super.close();
if (!client.isConnected()) {
throw new FTPException("Client not connected");
}
boolean cmdCompleted = client.completePendingCommand();
disconnect(client);
if (!cmdCompleted) {
throw new FTPException("Could not complete transfer, Reply Code - "
+ client.getReplyCode());
}
}
};
if (!FTPReply.isPositivePreliminary(client.getReplyCode())) {
// The ftpClient is an inconsistent state. Must close the stream
// which in turn will logout and disconnect from FTP server
fos.close();
throw new IOException("Unable to create file: " + file + ", Aborting");
}
return fos;
}
示例11: getNewFTPClient
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
public FTPClient getNewFTPClient(Uri path, int mode) throws SocketException, IOException, AuthenticationException{
// Use default port if not set
int port = path.getPort();
if (port<0) {
port = 21; // default port
}
String username="anonymous"; // default user
String password = ""; // default password
NetworkCredentialsDatabase database = NetworkCredentialsDatabase.getInstance();
Credential cred = database.getCredential(path.toString());
if(cred!=null){
password= cred.getPassword();
username = cred.getUsername();
}
FTPClient ftp= new FTPClient();
//try to connect
ftp.connect(path.getHost(), port);
//login to server
if(!ftp.login(username, password))
{
ftp.logout();
throw new AuthenticationException();
}
if(mode>=0){
ftp.setFileType(mode);
}
int reply = ftp.getReplyCode();
//FTPReply stores a set of constants for FTP reply codes.
if (!FTPReply.isPositiveCompletion(reply))
{
try {
ftp.disconnect();
} catch (IOException e) {
throw e;
}
return null;
}
//enter passive mode
ftp.enterLocalPassiveMode();
return ftp;
}
示例12: testPathNames
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
* Test of obscure path names in the FTP server
*
* RFC959 states that paths are constructed thus...
* <string> ::= <char> | <char><string>
* <pathname> ::= <string>
* <char> ::= any of the 128 ASCII characters except <CR> and <LF>
*
* So we need to check how high characters and problematic are encoded
*/
public void testPathNames() throws Exception
{
logger.debug("Start testPathNames");
FTPClient ftp = connectClient();
String PATH1="testPathNames";
try
{
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
fail("FTP server refused connection.");
}
boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN);
assertTrue("admin login successful", login);
reply = ftp.cwd("/Alfresco/User*Homes");
assertTrue(FTPReply.isPositiveCompletion(reply));
// Delete the root directory in case it was left over from a previous test run
try
{
ftp.removeDirectory(PATH1);
}
catch (IOException e)
{
// ignore this error
}
// make root directory for this test
boolean success = ftp.makeDirectory(PATH1);
assertTrue("unable to make directory:" + PATH1, success);
success = ftp.changeWorkingDirectory(PATH1);
assertTrue("unable to change to working directory:" + PATH1, success);
assertTrue("with a space", ftp.makeDirectory("test space"));
assertTrue("with exclamation", ftp.makeDirectory("space!"));
assertTrue("with dollar", ftp.makeDirectory("space$"));
assertTrue("with brackets", ftp.makeDirectory("space()"));
assertTrue("with hash curley brackets", ftp.makeDirectory("space{}"));
//Pound sign U+00A3
//Yen Sign U+00A5
//Capital Omega U+03A9
assertTrue("with pound sign", ftp.makeDirectory("pound \u00A3.world"));
assertTrue("with yen sign", ftp.makeDirectory("yen \u00A5.world"));
// Test steps that do not work
// assertTrue("with omega", ftp.makeDirectory("omega \u03A9.world"));
// assertTrue("with obscure ASCII chars", ftp.makeDirectory("?/.,<>"));
}
finally
{
// clean up tree if left over from previous run
ftp.disconnect();
}
}
示例13: testRenameCase
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
* Test of rename case ALF-20584
*
*/
public void testRenameCase() throws Exception
{
logger.debug("Start testRenameCase");
FTPClient ftp = connectClient();
String PATH1="testRenameCase";
try
{
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
fail("FTP server refused connection.");
}
boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN);
assertTrue("admin login successful", login);
reply = ftp.cwd("/Alfresco/User*Homes");
assertTrue(FTPReply.isPositiveCompletion(reply));
// Delete the root directory in case it was left over from a previous test run
try
{
ftp.removeDirectory(PATH1);
}
catch (IOException e)
{
// ignore this error
}
// make root directory for this test
boolean success = ftp.makeDirectory(PATH1);
assertTrue("unable to make directory:" + PATH1, success);
ftp.cwd(PATH1);
String FILE1_CONTENT_2="That's how it is says Pooh!";
ftp.storeFile("FileA.txt" , new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8")));
assertTrue("unable to rename", ftp.rename("FileA.txt", "FILEA.TXT"));
}
finally
{
// clean up tree if left over from previous run
ftp.disconnect();
}
}
示例14: testFtpQuotaAndFtp
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
* Test a quota failue exception over FTP.
* A file should not exist after a create and quota exception.
*/
public void testFtpQuotaAndFtp() throws Exception
{
// Enable usages
ContentUsageImpl contentUsage = (ContentUsageImpl)applicationContext.getBean("contentUsageImpl");
contentUsage.setEnabled(true);
contentUsage.init();
UserUsageTrackingComponent userUsageTrackingComponent = (UserUsageTrackingComponent)applicationContext.getBean("userUsageTrackingComponent");
userUsageTrackingComponent.setEnabled(true);
userUsageTrackingComponent.bootstrapInternal();
final String TEST_DIR="/Alfresco/User Homes/" + USER_THREE;
FTPClient ftpOne = connectClient();
try
{
int reply = ftpOne.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
fail("FTP server refused connection.");
}
boolean login = ftpOne.login(USER_THREE, PASSWORD_THREE);
assertTrue("user three login not successful", login);
boolean success = ftpOne.changeWorkingDirectory("Alfresco");
assertTrue("user three unable to cd to Alfreco", success);
success = ftpOne.changeWorkingDirectory("User*Homes");
assertTrue("user one unable to cd to User*Homes", success);
success = ftpOne.changeWorkingDirectory(USER_THREE);
assertTrue("user one unable to cd to " + USER_THREE, success);
/**
* Create a file as user three which is bigger than the quota
*/
String FILE3_CONTENT_3="test file 3 content that needs to be greater than 100 bytes to result in a quota exception being thrown";
String FILE1_NAME = "test.docx";
// Should not be success
success = ftpOne.appendFile(FILE1_NAME , new ByteArrayInputStream(FILE3_CONTENT_3.getBytes("UTF-8")));
assertFalse("user one can ignore quota", success);
boolean deleted = ftpOne.deleteFile(FILE1_NAME);
assertFalse("quota exception expected", deleted);
logger.debug("test done");
}
finally
{
// Disable usages
contentUsage.setEnabled(false);
contentUsage.init();
userUsageTrackingComponent.setEnabled(false);
userUsageTrackingComponent.bootstrapInternal();
ftpOne.dele(TEST_DIR);
if(ftpOne != null)
{
ftpOne.disconnect();
}
}
}
示例15: execute
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
* 执行FTP回调操作的方法
*
* @param <T> the type parameter
* @param callback 回调的函数
* @return the t
* @throws IOException the io exception
*/
public <T> T execute(FTPClientCallback<T> callback) throws IOException {
FTPClient ftp = new FTPClient();
try {
//登录FTP服务器
try {
//设置超时时间
ftp.setDataTimeout(7200);
//设置默认编码
ftp.setControlEncoding(DEAFULT_REMOTE_CHARSET);
//设置默认端口
ftp.setDefaultPort(DEAFULT_REMOTE_PORT);
//设置是否显示隐藏文件
ftp.setListHiddenFiles(false);
//连接ftp服务器
if (StringUtils.isNotEmpty(port) && NumberUtils.isDigits(port)) {
ftp.connect(host, Integer.valueOf(port));
} else {
ftp.connect(host);
}
} catch (ConnectException e) {
logger.error("连接FTP服务器失败:" + ftp.getReplyString() + ftp.getReplyCode());
throw new IOException("Problem connecting the FTP-server fail", e);
}
//得到连接的返回编码
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
}
//登录失败权限验证失败
if (!ftp.login(getUsername(), getPassword())) {
ftp.quit();
ftp.disconnect();
logger.error("连接FTP服务器用户或者密码失败::" + ftp.getReplyString());
throw new IOException("Cant Authentificate to FTP-Server");
}
if (logger.isDebugEnabled()) {
logger.info("成功登录FTP服务器:" + host + " 端口:" + port);
}
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
//回调FTP的操作
return callback.doTransfer(ftp);
} finally {
//FTP退出
ftp.logout();
//断开FTP连接
if (ftp.isConnected()) {
ftp.disconnect();
}
}
}