Java Code Examples for org.apache.commons.net.ftp.FTPFile#getName()

The following examples show how to use org.apache.commons.net.ftp.FTPFile#getName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FTPUtil.java    From anyline with Apache License 2.0 6 votes vote down vote up
private void downloadDir(File localDir){ 
	try{ 
		FTPFile[] files = client.listFiles(); 
        for(FTPFile file:files){ 
        	if(file.isDirectory()){ 
        		cd(file.getName()); 
        		downloadDir(new File(localDir+"/"+file.getName())); 
        	}else{ 
	        	File local = new File(localDir,file.getName()); 
        		downloadFile(this.dir+"/"+file.getName(), local); 
        	} 
        } 
       }catch(Exception e){ 
   		e.printStackTrace(); 
   	} 
}
 
Example 2
Source File: NetworkFile.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
public NetworkFile(NetworkFile dir, FTPFile file) {
	String name = file.getName();
	String dirPath = dir.getPath();
	host = dir.host;
	this.file = file;
	if (name == null) {
		throw new NullPointerException("name == null");
	}
	if (dirPath == null || dirPath.isEmpty()) {
		this.path = fixSlashes(name);
	} else if (name.isEmpty()) {
		this.path = fixSlashes(dirPath);
	} else {
		this.path = fixSlashes(join(dirPath, name));
	}
}
 
Example 3
Source File: NetworkFile.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
public NetworkFile(NetworkFile dir, FTPFile file) {
	String name = file.getName();
	String dirPath = dir.getPath();
	host = dir.host;
	this.file = file;
	if (name == null) {
		throw new NullPointerException("name == null");
	}
	if (dirPath == null || dirPath.isEmpty()) {
		this.path = fixSlashes(name);
	} else if (name.isEmpty()) {
		this.path = fixSlashes(dirPath);
	} else {
		this.path = fixSlashes(join(dirPath, name));
	}
}
 
Example 4
Source File: NetworkFile.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
public NetworkFile(NetworkFile dir, FTPFile file) {
	String name = file.getName();
	String dirPath = dir.getPath();
	host = dir.host;
	this.file = file;
	if (name == null) {
		throw new NullPointerException("name == null");
	}
	if (dirPath == null || dirPath.isEmpty()) {
		this.path = fixSlashes(name);
	} else if (name.isEmpty()) {
		this.path = fixSlashes(dirPath);
	} else {
		this.path = fixSlashes(join(dirPath, name));
	}
}
 
Example 5
Source File: FtpFileObject.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Lists the children of the file.
 */
@Override
protected String[] doListChildren() throws Exception {
    // List the children of this file
    doGetChildren();

    // VFS-210
    if (children == null) {
        return null;
    }

    // TODO - get rid of this children stuff
    final String[] childNames = new String[children.size()];
    int childNum = -1;
    final Iterator<FTPFile> iterChildren = children.values().iterator();
    while (iterChildren.hasNext()) {
        childNum++;
        final FTPFile child = iterChildren.next();
        childNames[childNum] = child.getName();
    }

    return UriParser.encode(childNames);
}
 
Example 6
Source File: FTPFileSystem.java    From RDFS with Apache License 2.0 6 votes vote down vote up
/**
 * Convert the file information in FTPFile to a {@link FileStatus} object. *
 * 
 * @param ftpFile
 * @param parentPath
 * @return FileStatus
 */
private FileStatus getFileStatus(FTPFile ftpFile, Path parentPath) {
  long length = ftpFile.getSize();
  boolean isDir = ftpFile.isDirectory();
  int blockReplication = 1;
  // Using default block size since there is no way in FTP client to know of
  // block sizes on server. The assumption could be less than ideal.
  long blockSize = DEFAULT_BLOCK_SIZE;
  long modTime = ftpFile.getTimestamp().getTimeInMillis();
  long accessTime = 0;
  FsPermission permission = getPermissions(ftpFile);
  String user = ftpFile.getUser();
  String group = ftpFile.getGroup();
  Path filePath = new Path(parentPath, ftpFile.getName());
  return new FileStatus(length, isDir, blockReplication, blockSize, modTime,
      accessTime, permission, user, group, filePath.makeQualified(this));
}
 
Example 7
Source File: FTPFileSystem.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * Convert the file information in FTPFile to a {@link FileStatus} object. *
 * 
 * @param ftpFile
 * @param parentPath
 * @return FileStatus
 */
private FileStatus getFileStatus(FTPFile ftpFile, Path parentPath) {
  long length = ftpFile.getSize();
  boolean isDir = ftpFile.isDirectory();
  int blockReplication = 1;
  // Using default block size since there is no way in FTP client to know of
  // block sizes on server. The assumption could be less than ideal.
  long blockSize = DEFAULT_BLOCK_SIZE;
  long modTime = ftpFile.getTimestamp().getTimeInMillis();
  long accessTime = 0;
  FsPermission permission = getPermissions(ftpFile);
  String user = ftpFile.getUser();
  String group = ftpFile.getGroup();
  Path filePath = new Path(parentPath, ftpFile.getName());
  return new FileStatus(length, isDir, blockReplication, blockSize, modTime,
      accessTime, permission, user, group, filePath.makeQualified(this));
}
 
Example 8
Source File: FTPUtils.java    From TranskribusCore with GNU General Public License v3.0 6 votes vote down vote up
public void downloadFile(String directory, FTPFile fileToDownload, File destFile, int fileType, FTPTransferListener transferL) throws IOException, InterruptedException {
	try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(destFile))) {
		logger.debug("setting filetype to: "+fileType);
		setFileType(fileType);
		enterLocalPassiveMode();
		setCopyStreamListener(transferL);
		transferL.setOutputStream(outputStream);
		transferL.setFTPClient(this);
		
		directory = FilenameUtils.normalizeNoEndSeparator(directory)+"/";
		
		boolean success = retrieveFile(directory + fileToDownload.getName(), outputStream);
		
		if (!success) {
			throw new IOException("Error while downloading " + fileToDownload.getName());
		} else if (transferL.isCanceled()) {
			throw new InterruptedException("Download cancelled!");
		} else {
			transferL.downloaded(100);
		}

		logout();
	} catch (IOException e) {
		throw e;
	}
}
 
Example 9
Source File: FTPFileSystem.java    From hadoop-gpu with Apache License 2.0 6 votes vote down vote up
/**
 * Convert the file information in FTPFile to a {@link FileStatus} object. *
 * 
 * @param ftpFile
 * @param parentPath
 * @return FileStatus
 */
private FileStatus getFileStatus(FTPFile ftpFile, Path parentPath) {
  long length = ftpFile.getSize();
  boolean isDir = ftpFile.isDirectory();
  int blockReplication = 1;
  // Using default block size since there is no way in FTP client to know of
  // block sizes on server. The assumption could be less than ideal.
  long blockSize = DEFAULT_BLOCK_SIZE;
  long modTime = ftpFile.getTimestamp().getTimeInMillis();
  long accessTime = 0;
  FsPermission permission = getPermissions(ftpFile);
  String user = ftpFile.getUser();
  String group = ftpFile.getGroup();
  Path filePath = new Path(parentPath, ftpFile.getName());
  return new FileStatus(length, isDir, blockReplication, blockSize, modTime,
      accessTime, permission, user, group, filePath.makeQualified(this));
}
 
Example 10
Source File: PooledFTPOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
public FTPInfo(FTPFile file, URI parent, URI self) throws UnsupportedEncodingException {
	this.file = file;
	this.parent = parent;
	String name = file.getName();
	Matcher m = FILENAME_PATTERN.matcher(name);
	if (m.matches()) {
		name = m.group(1); // some FTPs return full file paths as names, we want only the filename 
	}
	if (name.equals("/")) {
		name = ""; // root directory has no name
	} else if (name.endsWith(URIUtils.PATH_SEPARATOR)) {
		name = name.substring(0, name.length()-1);
	}
	this.name = name;
	// name is modified just for the URI
	if (file.isDirectory() && !name.endsWith(URIUtils.PATH_SEPARATOR)) {
		name = name + URIUtils.PATH_SEPARATOR;
	}
	if (self != null) {
		this.uri = self;
	} else {
		this.uri = URIUtils.getChildURI(parent, name);
	}
}
 
Example 11
Source File: FtpFileSystem.java    From iaf with Apache License 2.0 5 votes vote down vote up
protected String getDestinationFilename(FTPFile f, String destinationFolder, boolean createFolder, String action) throws FileSystemException {
	if(!folderExists(destinationFolder)) {
		if(createFolder) {
			createFolder(destinationFolder);
		}
		throw new FileSystemException("Cannot "+action+" file. Destination folder ["+destinationFolder+"] does not exist.");
	}
	return destinationFolder+"/"+f.getName();
}
 
Example 12
Source File: FtpResponse.java    From nutch-htmlunit with Apache License 2.0 5 votes vote down vote up
private byte[] list2html(List<FTPFile> list, String path, boolean includeDotDot) {

    //StringBuffer x = new StringBuffer("<!doctype html public \"-//ietf//dtd html//en\"><html><head>");
    StringBuffer x = new StringBuffer("<html><head>");
    x.append("<title>Index of "+path+"</title></head>\n");
    x.append("<body><h1>Index of "+path+"</h1><pre>\n");

    if (includeDotDot) {
      x.append("<a href='../'>../</a>\t-\t-\t-\n");
    }

    for (int i=0; i<list.size(); i++) {
      FTPFile f = (FTPFile) list.get(i);
      String name = f.getName();
      String time = HttpDateFormat.toString(f.getTimestamp());
      if (f.isDirectory()) {
        // some ftp server LIST "." and "..", we skip them here
        if (name.equals(".") || name.equals(".."))
          continue;
        x.append("<a href='"+name+"/"+"'>"+name+"/</a>\t");
        x.append(time+"\t-\n");
      } else if (f.isFile()) {
        x.append("<a href='"+name+    "'>"+name+"</a>\t");
        x.append(time+"\t"+f.getSize()+"\n");
      } else {
        // ignore isSymbolicLink()
        // ignore isUnknown()
      }
    }

    x.append("</pre></body></html>\n");

    return new String(x).getBytes();
  }
 
Example 13
Source File: FTPTransfer.java    From nifi with Apache License 2.0 5 votes vote down vote up
private FileInfo newFileInfo(final FTPFile file, String path) {
    if (file == null) {
        return null;
    }
    final File newFullPath = new File(path, file.getName());
    final String newFullForwardPath = newFullPath.getPath().replace("\\", "/");
    StringBuilder perms = new StringBuilder();
    perms.append(file.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION) ? "r" : "-");
    perms.append(file.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION) ? "w" : "-");
    perms.append(file.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION) ? "x" : "-");
    perms.append(file.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION) ? "r" : "-");
    perms.append(file.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.WRITE_PERMISSION) ? "w" : "-");
    perms.append(file.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION) ? "x" : "-");
    perms.append(file.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION) ? "r" : "-");
    perms.append(file.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.WRITE_PERMISSION) ? "w" : "-");
    perms.append(file.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION) ? "x" : "-");

    FileInfo.Builder builder = new FileInfo.Builder()
        .filename(file.getName())
        .fullPathFileName(newFullForwardPath)
        .directory(file.isDirectory())
        .size(file.getSize())
        .lastModifiedTime(file.getTimestamp().getTimeInMillis())
        .permissions(perms.toString())
        .owner(file.getUser())
        .group(file.getGroup());
    return builder.build();
}
 
Example 14
Source File: FTPPath.java    From NoNonsense-FilePicker with Mozilla Public License 2.0 5 votes vote down vote up
public FTPPath(@NonNull FTPPath mCurrentPath, @NonNull FTPFile file) {
    this.file = file;
    if (mCurrentPath.path.endsWith("/")) {
        this.path = mCurrentPath + file.getName();
    } else {
        this.path = mCurrentPath.path + "/" + file.getName();
    }
}
 
Example 15
Source File: FtpResponse.java    From anthelion with Apache License 2.0 5 votes vote down vote up
private byte[] list2html(List list, String path, boolean includeDotDot) {

    //StringBuffer x = new StringBuffer("<!doctype html public \"-//ietf//dtd html//en\"><html><head>");
    StringBuffer x = new StringBuffer("<html><head>");
    x.append("<title>Index of "+path+"</title></head>\n");
    x.append("<body><h1>Index of "+path+"</h1><pre>\n");

    if (includeDotDot) {
      x.append("<a href='../'>../</a>\t-\t-\t-\n");
    }

    for (int i=0; i<list.size(); i++) {
      FTPFile f = (FTPFile) list.get(i);
      String name = f.getName();
      String time = HttpDateFormat.toString(f.getTimestamp());
      if (f.isDirectory()) {
        // some ftp server LIST "." and "..", we skip them here
        if (name.equals(".") || name.equals(".."))
          continue;
        x.append("<a href='"+name+"/"+"'>"+name+"/</a>\t");
        x.append(time+"\t-\n");
      } else if (f.isFile()) {
        x.append("<a href='"+name+    "'>"+name+"</a>\t");
        x.append(time+"\t"+f.getSize()+"\n");
      } else {
        // ignore isSymbolicLink()
        // ignore isUnknown()
      }
    }

    x.append("</pre></body></html>\n");

    return new String(x).getBytes();
  }
 
Example 16
Source File: FtpConnection.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 把指定路径中的 FTPFile 类型文件,转换为 JFtpFile
 *
 * @param ftpFile             FTPFile 类型的文件
 * @param remoteDirectoryPath 文件所在目录
 * @return
 * @throws IOException
 */
private JFTPFile toFtpFile(FTPFile ftpFile, String remoteDirectoryPath) throws IOException {

    String name = ftpFile.getName();
    long fileSize = ftpFile.getSize();
    String fullPath = String.format("%s%s%s", remoteDirectoryPath, "/", ftpFile.getName()); // ftp 路径的分隔符都为 "/" ,所以 File.pathSeparator 不对
    long mTime = ftpFile.getTimestamp().getTime().getTime();
    //  logger.info(" 1.  getTimestamp : "+new DateTime(mTime).withZone(DateTimeZone.forTimeZone(TimeZone.getDefault())));
    // logger.info(" 2.  getTimestamp : "+ftpFile.getTimestamp().getTimeInMillis());

    return new JFTPFile(name, fileSize, fullPath, mTime, ftpFile.isDirectory());
}
 
Example 17
Source File: FtpUtil.java    From learning-taotaoMall with MIT License 5 votes vote down vote up
/** 
 * Description: 从FTP服务器下载文件 
 * @param host FTP服务器hostname 
 * @param port FTP服务器端口 
 * @param username FTP登录账号 
 * @param password FTP登录密码 
 * @param remotePath FTP服务器上的相对路径 
 * @param fileName 要下载的文件名 
 * @param localPath 下载后保存到本地的路径 
 * @return 
 */
public static boolean downloadFile(String host, int port, String username, String password, String remotePath, String fileName, String localPath) {
	boolean result = false;
	FTPClient ftp = new FTPClient();
	try {
		int reply;
		ftp.connect(host, port);
		// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
		ftp.login(username, password);// 登录
		reply = ftp.getReplyCode();
		if (!FTPReply.isPositiveCompletion(reply)) {
			ftp.disconnect();
			return result;
		}
		ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
		FTPFile[] fs = ftp.listFiles();
		for (FTPFile ff : fs) {
			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();
		result = true;
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		if (ftp.isConnected()) {
			try {
				ftp.disconnect();
			} catch (IOException ioe) {
			}
		}
	}
	return result;
}
 
Example 18
Source File: FTPTransfer.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private FileInfo newFileInfo(final FTPFile file, String path) {
    if (file == null) {
        return null;
    }
    final File newFullPath = new File(path, file.getName());
    final String newFullForwardPath = newFullPath.getPath().replace("\\", "/");
    StringBuilder perms = new StringBuilder();
    perms.append(file.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION) ? "r" : "-");
    perms.append(file.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION) ? "w" : "-");
    perms.append(file.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION) ? "x" : "-");
    perms.append(file.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION) ? "r" : "-");
    perms.append(file.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.WRITE_PERMISSION) ? "w" : "-");
    perms.append(file.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION) ? "x" : "-");
    perms.append(file.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION) ? "r" : "-");
    perms.append(file.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.WRITE_PERMISSION) ? "w" : "-");
    perms.append(file.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION) ? "x" : "-");

    FileInfo.Builder builder = new FileInfo.Builder()
        .filename(file.getName())
        .fullPathFileName(newFullForwardPath)
        .directory(file.isDirectory())
        .size(file.getSize())
        .lastModifiedTime(file.getTimestamp().getTimeInMillis())
        .permissions(perms.toString())
        .owner(file.getUser())
        .group(file.getGroup());
    return builder.build();
}
 
Example 19
Source File: FtpFileSystem.java    From iaf with Apache License 2.0 4 votes vote down vote up
@Override
public String getCanonicalName(FTPFile f) throws FileSystemException {
	return f.getName();
}
 
Example 20
Source File: FTPTransfer.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
private List<FileInfo> getListing(final String path, final int depth, final int maxResults) throws IOException {
    final List<FileInfo> listing = new ArrayList<>();
    if (maxResults < 1) {
        return listing;
    }

    if (depth >= 100) {
        logger.warn(this + " had to stop recursively searching directories at a recursive depth of " + depth + " to avoid memory issues");
        return listing;
    }

    final boolean ignoreDottedFiles = ctx.getProperty(FileTransfer.IGNORE_DOTTED_FILES).asBoolean();
    final boolean recurse = ctx.getProperty(FileTransfer.RECURSIVE_SEARCH).asBoolean();
    final String fileFilterRegex = ctx.getProperty(FileTransfer.FILE_FILTER_REGEX).getValue();
    final Pattern pattern = (fileFilterRegex == null) ? null : Pattern.compile(fileFilterRegex);
    final String pathFilterRegex = ctx.getProperty(FileTransfer.PATH_FILTER_REGEX).getValue();
    final Pattern pathPattern = (!recurse || pathFilterRegex == null) ? null : Pattern.compile(pathFilterRegex);
    final String remotePath = ctx.getProperty(FileTransfer.REMOTE_PATH).evaluateAttributeExpressions().getValue();

    // check if this directory path matches the PATH_FILTER_REGEX
    boolean pathFilterMatches = true;
    if (pathPattern != null) {
        Path reldir = path == null ? Paths.get(".") : Paths.get(path);
        if (remotePath != null) {
            reldir = Paths.get(remotePath).relativize(reldir);
        }
        if (reldir != null && !reldir.toString().isEmpty()) {
            if (!pathPattern.matcher(reldir.toString().replace("\\", "/")).matches()) {
                pathFilterMatches = false;
            }
        }
    }

    final FTPClient client = getClient(null);

    int count = 0;
    final FTPFile[] files;

    if (path == null || path.trim().isEmpty()) {
        files = client.listFiles(".");
    } else {
        files = client.listFiles(path);
    }
    if (files.length == 0 && path != null && !path.trim().isEmpty()) {
        // throw exception if directory doesn't exist
        final boolean cdSuccessful = setWorkingDirectory(path);
        if (!cdSuccessful) {
            throw new IOException("Cannot list files for non-existent directory " + path);
        }
    }

    for (final FTPFile file : files) {
        final String filename = file.getName();
        if (filename.equals(".") || filename.equals("..")) {
            continue;
        }

        if (ignoreDottedFiles && filename.startsWith(".")) {
            continue;
        }

        final File newFullPath = new File(path, filename);
        final String newFullForwardPath = newFullPath.getPath().replace("\\", "/");

        if (recurse && file.isDirectory()) {
            try {
                listing.addAll(getListing(newFullForwardPath, depth + 1, maxResults - count));
            } catch (final IOException e) {
                logger.error("Unable to get listing from " + newFullForwardPath + "; skipping this subdirectory");
            }
        }

        // if is not a directory and is not a link and it matches
        // FILE_FILTER_REGEX - then let's add it
        if (!file.isDirectory() && !file.isSymbolicLink() && pathFilterMatches) {
            if (pattern == null || pattern.matcher(filename).matches()) {
                listing.add(newFileInfo(file, path));
                count++;
            }
        }

        if (count >= maxResults) {
            break;
        }
    }

    return listing;
}