本文整理匯總了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();
}
}
}