本文整理匯總了Java中org.apache.commons.net.ftp.FTPClient類的典型用法代碼示例。如果您正苦於以下問題:Java FTPClient類的具體用法?Java FTPClient怎麽用?Java FTPClient使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
FTPClient類屬於org.apache.commons.net.ftp包,在下文中一共展示了FTPClient類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: download
import org.apache.commons.net.ftp.FTPClient; //導入依賴的package包/類
/**
* 下載文件
*
* @param remoteDir 遠程操作目錄
* @param remoteFileName 遠程下載文件名
* @param downloadFile 下載文件
* @return 下載結果<br> true - 下載成功<br>
* false - 下載失敗
*/
public boolean download(String remoteDir, String remoteFileName, File downloadFile) {
FTPClient ftp = null;
try {
ftp = initFtpClient(remoteDir);
if (ftp == null) {
logger.debug("ftp初始化失敗");
return false;
}
try (OutputStream os = new FileOutputStream(downloadFile)) {
boolean storeRet = ftp.retrieveFile(remoteFileName, os);
if (!storeRet) {
logger.debug("下載文件失敗");
return false;
}
}
return true;
} catch (IOException e) {
logger.error("FTP操作異常", e);
return false;
} finally {
close(ftp);
}
}
示例2: download
import org.apache.commons.net.ftp.FTPClient; //導入依賴的package包/類
public static byte[] download(String url, int port, String username, String password, String remotePath,
String fileName) throws IOException {
FTPClient ftp = new FTPClient();
ftp.setConnectTimeout(5000);
ftp.setAutodetectUTF8(true);
ftp.setCharset(CharsetUtil.UTF_8);
ftp.setControlEncoding(CharsetUtil.UTF_8.name());
try {
ftp.connect(url, port);
ftp.login(username, password);// 登錄
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
ftp.disconnect();
throw new IOException("login fail!");
}
ftp.changeWorkingDirectory(remotePath);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
try (ByteArrayOutputStream is = new ByteArrayOutputStream();) {
ftp.retrieveFile(ff.getName(), is);
byte[] result = is.toByteArray();
return result;
}
}
}
ftp.logout();
} finally {
if (ftp.isConnected()) {
ftp.disconnect();
}
}
return null;
}
示例3: mkdirs
import org.apache.commons.net.ftp.FTPClient; //導入依賴的package包/類
/**
* Convenience method, so that we don't open a new connection when using this
* method from within another method. Otherwise every API invocation incurs
* the overhead of opening/closing a TCP connection.
*/
private boolean mkdirs(FTPClient client, Path file, FsPermission permission)
throws IOException {
boolean created = true;
Path workDir = new Path(client.printWorkingDirectory());
Path absolute = makeAbsolute(workDir, file);
String pathName = absolute.getName();
if (!exists(client, absolute)) {
Path parent = absolute.getParent();
created = (parent == null || mkdirs(client, parent, FsPermission
.getDirDefault()));
if (created) {
String parentDir = parent.toUri().getPath();
client.changeWorkingDirectory(parentDir);
created = created && client.makeDirectory(pathName);
}
} else if (isFile(client, absolute)) {
throw new ParentNotDirectoryException(String.format(
"Can't make directory for path %s since it is a file.", absolute));
}
return created;
}
示例4: uploadFile
import org.apache.commons.net.ftp.FTPClient; //導入依賴的package包/類
/**
* 上傳文件至FTP服務器
*
* @author gaoxianglong
*/
public boolean uploadFile(File file) {
boolean result = false;
FTPClient ftpClient = ftpConnManager.getFTPClient();
if (null == ftpClient || !ftpClient.isConnected()) {
return result;
}
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file.getPath()))) {
boolean storeFile = ftpClient.storeFile(file.getName(), in);
if (storeFile) {
result = true;
log.info("file-->" + file.getPath() + "成功上傳至FTP服務器");
}
} catch (Exception e) {
log.error("error", e);
} finally {
disconnect(ftpClient);
}
return result;
}
示例5: downloadFile
import org.apache.commons.net.ftp.FTPClient; //導入依賴的package包/類
/**
* 從FTP服務器下載指定的文件至本地
*
* @author gaoxianglong
*/
public boolean downloadFile(File file) {
boolean result = false;
FTPClient ftpClient = ftpConnManager.getFTPClient();
if (null == ftpClient || !ftpClient.isConnected()) {
return result;
}
try (BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(System.getProperty("user.home") + "/" + file.getName()))) {
result = ftpClient.retrieveFile(file.getName(), out);
if (result) {
result = true;
log.info("file-->" + file.getPath() + "成功從FTP服務器下載");
}
} catch (Exception e) {
log.error("error", e);
} finally {
disconnect(ftpClient);
}
return result;
}
示例6: 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;
}
示例7: deleteFile
import org.apache.commons.net.ftp.FTPClient; //導入依賴的package包/類
/**
* 刪除文件
*
* @author wangwei
*/
public Map<String,String> deleteFile(String filename, String remoteFolder)
throws Exception {
Map<String,String> rs = new HashMap<String, String>();
// 連接FTP服務器
FTPClient ftp = this.connectFTPServer();
try {
// 改變當前路徑到指定路徑
this.changeDirectory(remoteFolder);
boolean result = ftp.deleteFile(filename);
if (!result) {
throw new Exception("FTP刪除文件失敗!");
}else{
rs.put("ret", "success");
}
} catch (Exception e) {
throw e;
}
return rs;
}
示例8: open
import org.apache.commons.net.ftp.FTPClient; //導入依賴的package包/類
@Override
public FSDataInputStream open(Path file, int bufferSize) throws IOException {
FTPClient client = connect();
Path workDir = new Path(client.printWorkingDirectory());
Path absolute = makeAbsolute(workDir, file);
FileStatus fileStat = getFileStatus(client, absolute);
if (fileStat.isDirectory()) {
disconnect(client);
throw new FileNotFoundException("Path " + file + " is a directory.");
}
client.allocate(bufferSize);
Path parent = absolute.getParent();
// Change to parent directory on the
// server. Only then can we read the
// file
// on the server by opening up an InputStream. 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
// FSDataInputStream.
client.changeWorkingDirectory(parent.toUri().getPath());
InputStream is = client.retrieveFileStream(file.getName());
FSDataInputStream fis = new FSDataInputStream(new FTPInputStream(is,
client, statistics));
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
fis.close();
throw new IOException("Unable to open file: " + file + ", Aborting");
}
return fis;
}
示例9: getFileStatus
import org.apache.commons.net.ftp.FTPClient; //導入依賴的package包/類
/**
* Convenience method, so that we don't open a new connection when using this
* method from within another method. Otherwise every API invocation incurs
* the overhead of opening/closing a TCP connection.
*/
private FileStatus getFileStatus(FTPClient client, Path file)
throws IOException {
FileStatus fileStat = null;
Path workDir = new Path(client.printWorkingDirectory());
Path absolute = makeAbsolute(workDir, file);
Path parentPath = absolute.getParent();
if (parentPath == null) { // root dir
long length = -1; // Length of root dir on server not known
boolean isDir = true;
int blockReplication = 1;
long blockSize = DEFAULT_BLOCK_SIZE; // Block Size not known.
long modTime = -1; // Modification time of root dir not known.
Path root = new Path("/");
return new FileStatus(length, isDir, blockReplication, blockSize,
modTime, root.makeQualified(this));
}
String pathName = parentPath.toUri().getPath();
FTPFile[] ftpFiles = client.listFiles(pathName);
if (ftpFiles != null) {
for (FTPFile ftpFile : ftpFiles) {
if (ftpFile.getName().equals(file.getName())) { // file found in dir
fileStat = getFileStatus(ftpFile, parentPath);
break;
}
}
if (fileStat == null) {
throw new FileNotFoundException("File " + file + " does not exist.");
}
} else {
throw new FileNotFoundException("File " + file + " does not exist.");
}
return fileStat;
}
示例10: getFTPClient
import org.apache.commons.net.ftp.FTPClient; //導入依賴的package包/類
public FTPClient getFTPClient(Uri uri) throws SocketException, IOException, AuthenticationException{
NetworkCredentialsDatabase database = NetworkCredentialsDatabase.getInstance();
Credential cred = database.getCredential(uri.toString());
if(cred==null){
cred = new Credential("anonymous","", buildKeyFromUri(uri).toString(), true);
}
FTPClient ftpclient = ftpClients.get(cred);
if (ftpclient!=null && ftpclient.isConnected()){
return ftpclient;
}
// Not previous session found, open a new one
Log.d(TAG, "create new ftp session for "+uri);
FTPClient ftp = getNewFTPClient(uri,FTP.BINARY_FILE_TYPE);
if(ftp==null)
return null;
Uri key = buildKeyFromUri(uri);
Log.d(TAG, "new ftp session created with key "+key);
ftpClients.put(cred, ftp);
return ftp;
}
示例11: getFTPSClient
import org.apache.commons.net.ftp.FTPClient; //導入依賴的package包/類
public FTPClient getFTPSClient(Uri uri) throws SocketException, IOException, AuthenticationException{
NetworkCredentialsDatabase database = NetworkCredentialsDatabase.getInstance();
Credential cred = database.getCredential(uri.toString());
if(cred==null){
cred = new Credential("anonymous","", buildKeyFromUri(uri).toString(), true);
}
FTPClient ftpclient = ftpsClients.get(cred);
if (ftpclient!=null && ftpclient.isConnected()){
return ftpclient;
}
// Not previous session found, open a new one
Log.d(TAG, "create new ftp session for "+uri);
FTPClient ftp = getNewFTPSClient(uri, FTP.BINARY_FILE_TYPE);
if(ftp==null)
return null;
Uri key = buildKeyFromUri(uri);
Log.d(TAG, "new ftp session created with key "+key);
ftpsClients.put(cred, ftp);
return ftp;
}
示例12: MKDAndCWD
import org.apache.commons.net.ftp.FTPClient; //導入依賴的package包/類
private boolean MKDAndCWD(FTPClient ftp, String remoteDir) throws IOException {
// 切分出所有子文件夾,按順序
String[] dirs = remoteDir.split("/");
// 遍曆文件夾
for (String subDir : dirs) {
// 文件夾字符串非空
if (!subDir.isEmpty()) {
// 切換工作目錄
if (!ftp.changeWorkingDirectory(subDir)) {
// 若目錄不存在則先創建
if (!ftp.makeDirectory(subDir)) {
return false;
}
// 切換工作目錄
if (!ftp.changeWorkingDirectory(subDir)) {
return false;
}
}
}
}
return true;
}
示例13: deleteFile
import org.apache.commons.net.ftp.FTPClient; //導入依賴的package包/類
/**
* 刪除服務器上指定的文件
*
* @author gaoxianglong
*/
public boolean deleteFile(File file) {
boolean result = false;
FTPClient ftpClient = ftpConnManager.getFTPClient();
if (null == ftpClient || !ftpClient.isConnected()) {
return result;
}
try {
result = ftpClient.deleteFile(file.getName());
if (result) {
result = true;
log.info("file-->" + file.getPath() + "成功從FTP服務器刪除");
}
} catch (Exception e) {
log.error("error", e);
} finally {
disconnect(ftpClient);
}
return result;
}
示例14: 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();
}
}
示例15: connectClient
import org.apache.commons.net.ftp.FTPClient; //導入依賴的package包/類
private FTPClient connectClient() throws IOException
{
FTPClient ftp = new FTPClient();
if(logger.isDebugEnabled())
{
ftp.addProtocolCommandListener(new PrintCommandListener(
new PrintWriter(System.out)));
}
ftp.connect(HOSTNAME, ftpConfigSection.getFTPPort());
return ftp;
}