/** * 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)); }
/** 获得目录下最大文件名 */ public String getMaxFileName(String remotePath) { try { ftpClient.changeWorkingDirectory(remotePath); FTPFile[] files = ftpClient.listFiles(); Arrays.sort(files, new Comparator<FTPFile>() { public int compare(FTPFile o1, FTPFile o2) { return o2.getName().compareTo(o1.getName()); } }); return files[0].getName(); } catch (IOException e) { logger.error("", e); throw new FtpException("FTP访问目录[" + remotePath + "]出错!", e); } }
/** * 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[] listStatus(FTPClient client, Path file) throws IOException { Path workDir = new Path(client.printWorkingDirectory()); Path absolute = makeAbsolute(workDir, file); FileStatus fileStat = getFileStatus(client, absolute); if (fileStat.isFile()) { return new FileStatus[] { fileStat }; } FTPFile[] ftpFiles = client.listFiles(absolute.toUri().getPath()); FileStatus[] fileStats = new FileStatus[ftpFiles.length]; for (int i = 0; i < ftpFiles.length; i++) { fileStats[i] = getFileStatus(ftpFiles[i], absolute); } return fileStats; }
/** * 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; }
/** * Parses a line of an z/OS - MVS FTP server file listing and converts it * into a usable format in the form of an <code> FTPFile </code> instance. * If the file listing line doesn't describe a file, then * <code> null </code> is returned. Otherwise a <code> FTPFile </code> * instance representing the file is returned. * * @param entry * A line of text from the file listing * @return An FTPFile instance corresponding to the supplied entry */ public FTPFile parseFTPEntry(String entry) { boolean isParsed = false; FTPFile f = new FTPFile(); if (isType == FILE_LIST_TYPE) { isParsed = parseFileList(f, entry); } else if (isType == MEMBER_LIST_TYPE) { isParsed = parseMemberList(f, entry); if (!isParsed) { isParsed = parseSimpleEntry(f, entry); } } else if (isType == UNIX_LIST_TYPE) { isParsed = parseUnixList(f, entry); } else if (isType == JES_LEVEL_1_LIST_TYPE) { isParsed = parseJeslevel1List(f, entry); } else if (isType == JES_LEVEL_2_LIST_TYPE) { isParsed = parseJeslevel2List(f, entry); } if (!isParsed) { f = null; } return f; }
private long getTotalRemoteFileSize(Collection<String> fileNames) { try { Future<Long> fileSizeResult = perform(() -> { return fileNames.stream() .map(rethrow((String fileName) -> { FTPFile[] ftpFiles = ftpClient.listFiles(fileName); if (ftpFiles.length != 1 || !ftpFiles[0].isFile()) { return 0L; } else { return ftpFiles[0].getSize(); } })) .mapToLong(Long::valueOf) .sum(); }); return AsyncUtil.getResult(fileSizeResult); } catch (ExecutionException e) { LOGGER.warn("Error while calculating download file size, progress will not be available."); LogUtil.stacktrace(LOGGER, e); return 0; } }
/** * 下载 * * @param remotePath 下载目录 * @param localPath 本地目录 * @return * @throws Exception */ public boolean downLoadFile(String remotePath, String localPath) throws FtpException { synchronized (LOCK) { try { if (ftpClient.changeWorkingDirectory(remotePath)) {// 转移到FTP服务器目录 FTPFile[] files = ftpClient.listFiles(); if (files.length > 0) { File localdir = new File(localPath); if (!localdir.exists()) { localdir.mkdir(); } } for (FTPFile ff : files) { if (!downLoadFile(ff, localPath)) { return false; } } return files.length > 0; } } catch (IOException e) { logger.error("", e); throw new FtpException("FTP下载[" + localPath + "]出错!", e); } return false; } }
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)); } }
@Test public void testParseFTPEntryExpected() { FTPFileEntryParser parser = new FTPParserSelector().getParser("UNIX"); FTPFile parsed; parsed = parser.parseFTPEntry( "drw-rw-rw- 1 user ftp 0 Mar 11 20:56 ADMIN_Documentation"); assertNotNull(parsed); assertEquals(parsed.getType(), FTPFile.DIRECTORY_TYPE); assertEquals("user", parsed.getUser()); assertEquals("ftp", parsed.getGroup()); assertEquals("ADMIN_Documentation", parsed.getName()); parsed = parser.parseFTPEntry( "drwxr--r-- 1 user group 0 Feb 14 18:14 Downloads"); assertNotNull(parsed); assertEquals("Downloads", parsed.getName()); }
@Test public void testCurrentYear() { FTPFileEntryParser parser = new FTPParserSelector().getParser("UNIX"); FTPFile parsed; parsed = parser.parseFTPEntry( "-rw-r--r-- 1 20708 205 194 Oct 17 14:40 D3I0_805.fixlist"); assertNotNull(parsed); assertTrue(parsed.isFile()); assertNotNull(parsed.getTimestamp()); assertEquals(Calendar.OCTOBER, parsed.getTimestamp().get(Calendar.MONTH)); assertEquals(17, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH)); assertEquals(14, parsed.getTimestamp().get(Calendar.HOUR_OF_DAY)); assertEquals(40, parsed.getTimestamp().get(Calendar.MINUTE)); }
private Map<String, FTPFile> listFilesRecursively(String directory) throws IOException { FTPFile[] listFiles = ftpClient.listFiles(directory); List<FTPFile> ftpFiles = Arrays.asList(listFiles); Map<String, FTPFile> fileMap = new HashMap<>(); ftpFiles.stream() .filter(FTPFile::isFile) .filter(file -> !file.getName().endsWith(".md5")) .forEach(file -> { fileMap.put(directory + '/' + file.getName(), file); }); ftpFiles.stream() .filter(FTPFile::isDirectory) .map(rethrow((FTPFile dir) -> listFilesRecursively(directory + '/' + dir.getName()))) .forEach(fileMap::putAll); return fileMap; }
@Test public void testLowerCaseMonths() { FTPFileEntryParser parser = new FTPParserSelector().getParser("UNIX"); FTPFile parsed; parsed = parser.parseFTPEntry( "drwxrwxrwx 41 spinkb spinkb 1394 jan 21 20:57 Desktop"); assertNotNull(parsed); assertEquals("Desktop", parsed.getName()); assertEquals(FTPFile.DIRECTORY_TYPE, parsed.getType()); assertEquals("spinkb", parsed.getUser()); assertEquals("spinkb", parsed.getGroup()); assertNotNull(parsed.getTimestamp()); assertEquals(Calendar.JANUARY, parsed.getTimestamp().get(Calendar.MONTH)); assertEquals(21, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH)); }
@Test public void testUpperCaseMonths() { FTPFileEntryParser parser = new FTPParserSelector().getParser("UNIX"); FTPFile parsed; parsed = parser.parseFTPEntry( "drwxrwxrwx 41 spinkb spinkb 1394 Feb 21 20:57 Desktop"); assertNotNull(parsed); assertEquals("Desktop", parsed.getName()); assertEquals(FTPFile.DIRECTORY_TYPE, parsed.getType()); assertEquals("spinkb", parsed.getUser()); assertEquals("spinkb", parsed.getGroup()); assertEquals(Calendar.FEBRUARY, parsed.getTimestamp().get(Calendar.MONTH)); assertEquals(21, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH)); }
@Override public Cursor queryChildDocuments(String parentDocumentId, String[] projection, String sortOrder) throws FileNotFoundException { final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection)); final NetworkFile parent = getFileForDocId(parentDocumentId); final NetworkConnection connection = getNetworkConnection(parentDocumentId); try { connection.getConnectedClient().changeWorkingDirectory(parent.getPath()); for (FTPFile file : connection.getConnectedClient().listFiles()) { includeFile(result, null, new NetworkFile(parent, file)); } } catch (IOException e) { CrashReportingManager.logException(e); } return result; }
@Test public void testSetuid() { FTPFileEntryParser parser = new FTPParserSelector().getParser("UNIX"); FTPFile parsed; parsed = parser.parseFTPEntry( "drwsr--r-- 1 user group 0 Feb 29 18:14 Filename" ); assertNotNull(parsed); assertTrue(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION)); parsed = parser.parseFTPEntry( "drwSr--r-- 1 user group 0 Feb 29 18:14 Filename" ); assertNotNull(parsed); assertFalse(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION)); }
@Test public void testSetgid() { FTPFileEntryParser parser = new FTPParserSelector().getParser("UNIX"); FTPFile parsed; parsed = parser.parseFTPEntry( "drwxr-sr-- 1 user group 0 Feb 29 18:14 Filename" ); assertNotNull(parsed); assertTrue(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION)); parsed = parser.parseFTPEntry( "drwxr-Sr-- 1 user group 0 Feb 29 18:14 Filename" ); assertNotNull(parsed); assertFalse(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION)); }
@Test public void testStickyBit() { FTPFileEntryParser parser = new FTPParserSelector().getParser("UNIX"); FTPFile parsed; parsed = parser.parseFTPEntry( "drwxr--r-t 1 user group 0 Feb 29 18:14 Filename" ); assertNotNull(parsed); assertTrue(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION)); parsed = parser.parseFTPEntry( "drwxr--r-T 1 user group 0 Feb 29 18:14 Filename" ); assertNotNull(parsed); assertFalse(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION)); }
@Test public void testParse() throws Exception { FTPFile parsed; // #3689 parsed = parser.parseFTPEntry( "drwxr-xr-x+ 5 niels staff 7 Sep 6 13:46 data" ); assertNotNull(parsed); assertEquals(parsed.getName(), "data"); assertEquals(FTPFile.DIRECTORY_TYPE, parsed.getType()); assertEquals(7, parsed.getSize()); assertEquals(Calendar.SEPTEMBER, parsed.getTimestamp().get(Calendar.MONTH)); assertEquals(6, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH)); assertTrue(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION)); assertTrue(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION)); assertTrue(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION)); assertTrue(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION)); assertTrue(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION)); assertTrue(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION)); assertTrue(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION)); }
/** * http://trac.cyberduck.ch/ticket/1198 */ @Test public void testFile() { FTPFile parsed; parsed = parser.parseFTPEntry( "-r--r--r-- 0 165100 165100 Aug 1 10:24 grau2.tif" ); assertNotNull(parsed); assertEquals("grau2.tif", parsed.getName()); assertEquals(FTPFile.FILE_TYPE, parsed.getType()); assertEquals(Calendar.AUGUST, parsed.getTimestamp().get(Calendar.MONTH)); assertEquals(1, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH)); assertEquals(10, parsed.getTimestamp().get(Calendar.HOUR_OF_DAY)); assertEquals(24, parsed.getTimestamp().get(Calendar.MINUTE)); assertTrue(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION)); assertTrue(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION)); assertTrue(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION)); assertFalse(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION)); assertFalse(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.WRITE_PERMISSION)); assertFalse(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.WRITE_PERMISSION)); assertFalse(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION)); assertFalse(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION)); assertFalse(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION)); }
/** * http://trac.cyberduck.ch/ticket/1198 */ @Test public void testFolder() { FTPFile parsed; parsed = parser.parseFTPEntry( "dr--r--r-- folder 0 Aug 1 10:18 TestCyberduck" ); assertNotNull(parsed); assertEquals("TestCyberduck", parsed.getName()); assertEquals(FTPFile.DIRECTORY_TYPE, parsed.getType()); assertEquals(Calendar.AUGUST, parsed.getTimestamp().get(Calendar.MONTH)); assertEquals(1, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH)); assertEquals(10, parsed.getTimestamp().get(Calendar.HOUR_OF_DAY)); assertEquals(18, parsed.getTimestamp().get(Calendar.MINUTE)); assertTrue(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION)); assertTrue(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION)); assertTrue(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION)); assertFalse(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION)); assertFalse(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.WRITE_PERMISSION)); assertFalse(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.WRITE_PERMISSION)); assertFalse(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION)); assertFalse(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION)); assertFalse(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION)); }
@Test public void testReadonlyFile() { FTPFile parsed = parser.parseFTPEntry("+m825718503,r,s280,\tdjb.html\r\n"); assertEquals("djb.html", parsed.getName()); assertFalse(parsed.isDirectory()); assertEquals(280, parsed.getSize(), 0); long millis = 825718503; millis = millis * 1000; assertEquals(millis, parsed.getTimestamp().getTimeInMillis()); assertEquals(FTPFile.FILE_TYPE, parsed.getType()); assertFalse(parsed.isDirectory()); assertTrue(parsed.isFile()); assertFalse(parsed.isSymbolicLink()); // assertEquals("owner", "Unknown", parsed.getUser()); // assertEquals("group", "Unknown", parsed.getGroup()); // assertEquals("permissions", "r--r--r-- (444)", parsed.attributes.getPermission().toString()); }
@Test public void testReadonlyDirectory() { FTPFile parsed = parser.parseFTPEntry("+m825718503,/,\t514"); assertEquals("514", parsed.getName()); assertTrue(parsed.isDirectory()); // assertEquals("size", -1, parsed.getSize(), 0); long millis = 825718503; millis = millis * 1000; assertEquals(millis, parsed.getTimestamp().getTimeInMillis()); assertEquals(FTPFile.DIRECTORY_TYPE, parsed.getType()); assertTrue(parsed.isDirectory()); assertFalse(parsed.isFile()); assertFalse(parsed.isSymbolicLink()); // assertEquals("owner", "Unknown", parsed.getUser()); // assertEquals("group", "Unknown", parsed.getGroup()); // assertEquals("permissions", "r-xr-xr-x (555)", parsed.getPermission().toString()); }
/** * 从远程服务器目录下载文件到本地服务器目录中 * * @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; }
@Test public void testParse() throws Exception { FTPFile parsed; //#1213 parsed = parser.parseFTPEntry( "-rw-r--r-- FTP User 10439 Apr 20 05:29 ASCheckbox_2_0.zip" ); assertNotNull(parsed); assertEquals("ASCheckbox_2_0.zip", parsed.getName()); assertEquals(FTPFile.FILE_TYPE, parsed.getType()); assertEquals(10439, parsed.getSize()); assertEquals(Calendar.APRIL, parsed.getTimestamp().get(Calendar.MONTH)); assertEquals(20, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH)); assertTrue(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION)); assertTrue(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION)); assertTrue(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION)); assertTrue(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION)); assertFalse(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.WRITE_PERMISSION)); assertFalse(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.WRITE_PERMISSION)); assertFalse(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION)); assertFalse(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION)); assertFalse(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION)); }
@Test public void testParse() throws Exception { FTPFile parsed; // #3119 parsed = parser.parseFTPEntry( "-rw-r--r-- 1 ftp ftp 100847 Sep 10 2004 octfront2.jpg" ); assertNotNull(parsed); assertEquals("octfront2.jpg", parsed.getName()); assertEquals(FTPFile.FILE_TYPE, parsed.getType()); assertEquals(100847, parsed.getSize()); assertEquals(Calendar.SEPTEMBER, parsed.getTimestamp().get(Calendar.MONTH)); assertEquals(10, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH)); assertTrue(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION)); assertTrue(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION)); assertTrue(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION)); assertTrue(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION)); }
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; }
private FsAction getFsAction(int accessGroup, FTPFile ftpFile) { FsAction action = FsAction.NONE; if (ftpFile.hasPermission(accessGroup, FTPFile.READ_PERMISSION)) { action.or(FsAction.READ); } if (ftpFile.hasPermission(accessGroup, FTPFile.WRITE_PERMISSION)) { action.or(FsAction.WRITE); } if (ftpFile.hasPermission(accessGroup, FTPFile.EXECUTE_PERMISSION)) { action.or(FsAction.EXECUTE); } return action; }
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; }
@Override public FileInfo getRemoteFileInfo(final FlowFile flowFile, String path, String remoteFileName) throws IOException { final FTPClient client = getClient(flowFile); if (path == null) { int slashpos = remoteFileName.lastIndexOf('/'); if (slashpos >= 0 && !remoteFileName.endsWith("/")) { path = remoteFileName.substring(0, slashpos); remoteFileName = remoteFileName.substring(slashpos + 1); } else { path = ""; } } final FTPFile[] files = client.listFiles(path); FTPFile matchingFile = null; for (final FTPFile file : files) { if (file.getName().equalsIgnoreCase(remoteFileName)) { matchingFile = file; break; } } if (matchingFile == null) { return null; } return newFileInfo(matchingFile, path); }
/** * 获取指定目录下的文件与目录信息集合 * * @param currentDir 指定的当前目录 * @return 返回的文件集合 */ public FTPFile[] GetDirAndFilesInfo(FTPClient ftpClient, String currentDir) { FTPFile[] files = null; try { if (currentDir == null) files = ftpClient.listFiles(); else files = ftpClient.listFiles(currentDir); } catch (IOException ex) { logger.error(ex.getMessage(), ex); //e.printStackTrace() } return files; }
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; }
private FsPermission getPermissions(FTPFile ftpFile) { FsAction user, group, others; user = getFsAction(FTPFile.USER_ACCESS, ftpFile); group = getFsAction(FTPFile.GROUP_ACCESS, ftpFile); others = getFsAction(FTPFile.WORLD_ACCESS, ftpFile); return new FsPermission(user, group, others); }
/** * Parses a line of an z/OS - MVS FTP server file listing and converts it * into a usable format in the form of an <code> FTPFile </code> instance. * If the file listing line doesn't describe a file, then * <code> null </code> is returned. Otherwise a <code> FTPFile </code> * instance representing the file is returned. * * @param entry * A line of text from the file listing * @return An FTPFile instance corresponding to the supplied entry */ // @Override public FTPFile parseFTPEntry(String entry) { boolean isParsed = false; FTPFile f = new FTPFile(); if (isType == FILE_LIST_TYPE) { isParsed = parseFileList(f, entry); } else if (isType == MEMBER_LIST_TYPE) { isParsed = parseMemberList(f, entry); if (!isParsed) { isParsed = parseSimpleEntry(f, entry); } } else if (isType == UNIX_LIST_TYPE) { isParsed = parseUnixList(f, entry); } else if (isType == JES_LEVEL_1_LIST_TYPE) { isParsed = parseJeslevel1List(f, entry); } else if (isType == JES_LEVEL_2_LIST_TYPE) { isParsed = parseJeslevel2List(f, entry); } if (!isParsed) { f = null; } return f; }
/** * Assigns the name to the first word of the entry. Only to be used from a * safe context, for example from a memberlist, where the regex for some * reason fails. Then just assign the name field of FTPFile. * * @param file * @param entry * @return true if the entry string is non-null and non-empty */ private boolean parseSimpleEntry(FTPFile file, String entry) { if (entry != null && entry.trim().length() > 0) { file.setRawListing(entry); String name = entry.split(" ")[0]; file.setName(name); file.setType(FTPFile.FILE_TYPE); return true; } return false; }