本文整理汇总了Java中org.apache.commons.net.ftp.FTPClient.changeWorkingDirectory方法的典型用法代码示例。如果您正苦于以下问题:Java FTPClient.changeWorkingDirectory方法的具体用法?Java FTPClient.changeWorkingDirectory怎么用?Java FTPClient.changeWorkingDirectory使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.commons.net.ftp.FTPClient
的用法示例。
在下文中一共展示了FTPClient.changeWorkingDirectory方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: 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;
}
示例2: 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;
}
示例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: 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;
}
示例5: uploadDirectory
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
* Recursively upload a directory to FTP server with the provided FTP client object.
*
* @param sourceDirectoryPath
* @param targetDirectoryPath
* @param logPrefix
* @throws IOException
*/
protected void uploadDirectory(final FTPClient ftpClient, final String sourceDirectoryPath,
final String targetDirectoryPath, final String logPrefix) throws IOException {
log.info(String.format(UPLOAD_DIR, logPrefix, sourceDirectoryPath, targetDirectoryPath));
final File sourceDirectory = new File(sourceDirectoryPath);
final File[] files = sourceDirectory.listFiles();
if (files == null || files.length == 0) {
log.info(String.format("%sEmpty directory at %s", logPrefix, sourceDirectoryPath));
return;
}
// Make sure target directory exists
final boolean isTargetDirectoryExist = ftpClient.changeWorkingDirectory(targetDirectoryPath);
if (!isTargetDirectoryExist) {
ftpClient.makeDirectory(targetDirectoryPath);
}
final String nextLevelPrefix = logPrefix + "..";
for (File file : files) {
if (file.isFile()) {
uploadFile(ftpClient, file.getAbsolutePath(), targetDirectoryPath, nextLevelPrefix);
} else {
uploadDirectory(ftpClient, Paths.get(sourceDirectoryPath, file.getName()).toString(),
targetDirectoryPath + "/" + file.getName(), nextLevelPrefix);
}
}
}
示例6: downloadFolderFiles
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
* 从远程服务器目录下载文件到本地服务器目录中
*
* @param ftp ftp对象
* @param localdir 本地文件夹路径
* @param remotedir 远程文件夹路径
* @param localTmpFile 本地下载文件名记录
* @return
* @throws IOException
*/
private Collection<String> downloadFolderFiles(FTPClient ftp, final String localdir, final String remotedir, final String localTmpFile) throws IOException {
//切换到下载目录的中
ftp.changeWorkingDirectory(remotedir);
//获取目录中所有的文件信息
FTPFile[] ftpfiles = ftp.listFiles();
Collection<String> fileNamesCol = new ArrayList<>();
//判断文件目录是否为空
if (!ArrayUtils.isEmpty(ftpfiles)) {
for (FTPFile ftpfile : ftpfiles) {
String remoteFilePath = ftpfile.getName();
String localFilePath = localdir + separator + ftpfile.getName();
//System.out.println("remoteFilePath ="+remoteFilePath +" localFilePath="+localFilePath)
//单个文件下载状态
DownloadStatus downStatus = FtpHelper.getInstance().download(ftp, remoteFilePath, localFilePath);
if (downStatus == DownloadStatus.Download_New_Success) {
//临时目录中添加记录信息
fileNamesCol.add(remoteFilePath);
}
}
}
if (!fileNamesCol.isEmpty() && !StringUtils.isEmpty(localTmpFile)) {
FileOperateUtils.writeLinesToFile(fileNamesCol, localTmpFile, false);
}
return fileNamesCol;
}
示例7: listSequentialDatasets
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
public static List<String> listSequentialDatasets(
String pdsName, Configuration conf) throws IOException {
List<String> datasets = new ArrayList<String>();
FTPClient ftp = null;
try {
ftp = getFTPConnection(conf);
if (ftp != null) {
ftp.changeWorkingDirectory("'" + pdsName + "'");
FTPFile[] ftpFiles = ftp.listFiles();
for (FTPFile f : ftpFiles) {
if (f.getType() == FTPFile.FILE_TYPE) {
datasets.add(f.getName());
}
}
}
} catch(IOException ioe) {
throw new IOException ("Could not list datasets from " + pdsName + ":"
+ ioe.toString());
} finally {
if (ftp != null) {
closeFTPConnection(ftp);
}
}
return datasets;
}
示例8: uploadFileToWebApp
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
* Uploads a file to an Azure web app.
* @param profile the publishing profile for the web app.
* @param fileName the name of the file on server
* @param file the local file
*/
public static void uploadFileToWebApp(PublishingProfile profile, String fileName, InputStream file) {
FTPClient ftpClient = new FTPClient();
String[] ftpUrlSegments = profile.ftpUrl().split("/", 2);
String server = ftpUrlSegments[0];
String path = "./site/wwwroot/webapps";
if (fileName.contains("/")) {
int lastslash = fileName.lastIndexOf('/');
path = path + "/" + fileName.substring(0, lastslash);
fileName = fileName.substring(lastslash + 1);
}
try {
ftpClient.connect(server);
ftpClient.login(profile.ftpUsername(), profile.ftpPassword());
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
for (String segment : path.split("/")) {
if (!ftpClient.changeWorkingDirectory(segment)) {
ftpClient.makeDirectory(segment);
ftpClient.changeWorkingDirectory(segment);
}
}
ftpClient.storeFile(fileName, file);
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
示例9: 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;
}
示例10: uploadFileToFunctionApp
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
* Uploads a file to an Azure function app.
* @param profile the publishing profile for the web app.
* @param fileName the name of the file on server
* @param file the local file
*/
public static void uploadFileToFunctionApp(PublishingProfile profile, String fileName, InputStream file) {
FTPClient ftpClient = new FTPClient();
String[] ftpUrlSegments = profile.ftpUrl().split("/", 2);
String server = ftpUrlSegments[0];
String path = "site/wwwroot";
if (fileName.contains("/")) {
int lastslash = fileName.lastIndexOf('/');
path = path + "/" + fileName.substring(0, lastslash);
fileName = fileName.substring(lastslash + 1);
}
try {
ftpClient.connect(server);
ftpClient.login(profile.ftpUsername(), profile.ftpPassword());
ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
for (String segment : path.split("/")) {
if (!ftpClient.changeWorkingDirectory(segment)) {
ftpClient.makeDirectory(segment);
ftpClient.changeWorkingDirectory(segment);
}
}
ftpClient.storeFile(fileName, file);
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
示例11: 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;
}
示例12: 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;
}
示例13: 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();
}
}
示例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: buildFileTree
import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
private void buildFileTree(TreeItem treeNode, FTPClient client) throws Exception {
// display the files
FTPFile[] files = client.listFiles("", FTPFile::isFile);
for (FTPFile file : files) {
if(!file.getName().startsWith(".")) {
System.out.println("File: " + file.getName());
// add file to file tree
treeNode.getChildren().add(new TreeItem<>(getFileDisplayText(client, file)));
} // if
} // for
// get the directories
FTPFile[] directories = client.listDirectories();
for (FTPFile dir : directories) {
if(!dir.getName().startsWith(".")) {
// change working directory to detected directory
client.changeWorkingDirectory(dir.getName());
// save working dir
String pwd = client.printWorkingDirectory();
// create treeItem to represent new Directory
TreeItem newDir = new TreeItem<>(dir.getName(), new ImageView(dirIcon));
newDir.setExpanded(false);
// add directory to file tree
treeNode.getChildren().add(newDir);
Platform.runLater(() -> logTA.appendText("\nDiscovering Files in: " + pwd));
System.out.println("Discovering Files in: " + pwd);
// recursively call method to add files and directories to new directory
buildFileTree(newDir, client);
// go back to parent directory, once finished in this directory
client.changeToParentDirectory();
} // if
} // for
}