Java Code Examples for org.apache.commons.net.ftp.ftpclient#listFiles()

The following examples show how to use org.apache.commons.net.ftp.ftpclient#listFiles() . 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: FileUtils.java    From webcurator with Apache License 2.0 7 votes vote down vote up
public static void removeFTPDirectory(FTPClient ftpClient, String directoryName) {
	try {
    	ftpClient.changeWorkingDirectory(directoryName);
    	for (FTPFile file : ftpClient.listFiles()) {
    		if (file.isDirectory()) {
    			FileUtils.removeFTPDirectory(ftpClient, file.getName());
    		} else {
        	    log.debug("Deleting " + file.getName());
    			ftpClient.deleteFile(file.getName());
    		}
    	}
    	ftpClient.changeWorkingDirectory(directoryName);
    	ftpClient.changeToParentDirectory();
	    log.debug("Deleting " + directoryName);
    	ftpClient.removeDirectory(directoryName);
	} catch (Exception ex) {
		
	}
}
 
Example 2
Source File: MainframeFTPClientUtils.java    From aliyun-maxcompute-data-collectors with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 3
Source File: FTPFileSystem.java    From RDFS with Apache License 2.0 6 votes vote down vote up
/**
 * 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.isDir()) {
    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;
}
 
Example 4
Source File: FTPFileSystem.java    From hadoop-gpu with Apache License 2.0 6 votes vote down vote up
/**
 * 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.isDir()) {
    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;
}
 
Example 5
Source File: FTPFileSystem.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 6
Source File: FTPClientUtils.java    From springboot-ureport with Apache License 2.0 6 votes vote down vote up
/**
 *  获取全部的文件列表
 * @param path 路径
 * @return
 */
public List<FTPFile> getFileList(String path){
	List<FTPFile> list = new ArrayList<>();
	FTPClient ftpClient = borrowObject();
	try {
		FTPFile[] listFiles = ftpClient.listFiles(path);
		for (FTPFile ftpFile : listFiles) {
			byte[] bytes = ftpFile.getName().getBytes("iso-8859-1");
			ftpFile.setName(new String(bytes, "GBK"));
			list.add(ftpFile);
		}
	} catch (IOException e) {
		e.printStackTrace();
		throw new RuntimeException(e);
	}finally {
		returnObject(ftpClient);
	}
	return  list;
}
 
Example 7
Source File: FTPServerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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();
    }       
}
 
Example 8
Source File: FTPTransfer.java    From nifi with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 9
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 10
Source File: FTPFileSystem.java    From hadoop-gpu with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 11
Source File: FtpConnectionFactory.java    From BigDataScript with Apache License 2.0 5 votes vote down vote up
/**
 * List files using an FTP client
 */
public FTPFile[] listFiles(FTPClient ftp, URI uri) {
	synchronized (ftp) {
		try {
			return ftp.listFiles(uri.getPath());
		} catch (IOException e) {
			String msg = "Error reading remote directory '" + uri + "'";
			Timer.showStdErr(msg);
			throw new RuntimeException(msg, e);
		}
	}
}
 
Example 12
Source File: FTPFileSystem.java    From RDFS with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 13
Source File: FTPTransfer.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 14
Source File: FTPServerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
     * Test CWD for FTP server
     * 
     * @throws Exception
     */
    public void testCWD() throws Exception
    {
        logger.debug("Start testCWD");
        
        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 successful", login);
            
            FTPFile[] files = ftp.listFiles();
            reply = ftp.getReplyCode();
            assertTrue(FTPReply.isPositiveCompletion(reply));

            assertTrue(files.length == 1);
            
            boolean foundAlfresco=false;
            for(FTPFile file : files)
            {
                logger.debug("file name=" + file.getName());
                assertTrue(file.isDirectory());
                
                if(file.getName().equalsIgnoreCase("Alfresco"))
                {
                    foundAlfresco=true;
                }
            }
            assertTrue(foundAlfresco);
            
            // Change to Alfresco Dir that we know exists
            reply = ftp.cwd("/Alfresco");
            assertTrue(FTPReply.isPositiveCompletion(reply));
            
            // relative path with space char
            reply = ftp.cwd("Data Dictionary");
            assertTrue(FTPReply.isPositiveCompletion(reply));
            
            // non existant absolute
            reply = ftp.cwd("/Garbage");
            assertTrue(FTPReply.isNegativePermanent(reply));
            
            reply = ftp.cwd("/Alfresco/User Homes");
            assertTrue(FTPReply.isPositiveCompletion(reply));
            
            // Wild card
            reply = ftp.cwd("/Alfresco/User*Homes");
            assertTrue("unable to change to /Alfresco User*Homes/", FTPReply.isPositiveCompletion(reply));
            
//            // Single char pattern match
//            reply = ftp.cwd("/Alfre?co");
//            assertTrue("Unable to match single char /Alfre?co", FTPReply.isPositiveCompletion(reply));
            
            // two level folder
            reply = ftp.cwd("/Alfresco/Data Dictionary");
            assertTrue("unable to change to /Alfresco/Data Dictionary", FTPReply.isPositiveCompletion(reply));
            
            // go up one
            reply = ftp.cwd("..");
            assertTrue("unable to change to ..", FTPReply.isPositiveCompletion(reply));
            
            reply = ftp.pwd();
            ftp.getStatus();
            
            assertTrue("unable to get status", FTPReply.isPositiveCompletion(reply));
            
            // check we are at the correct point in the tree
            reply = ftp.cwd("Data Dictionary");
            assertTrue(FTPReply.isPositiveCompletion(reply));
            

        } 
        finally
        {
            ftp.disconnect();
        }    

    }
 
Example 15
Source File: FTPServerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Test CRUD for FTP server
 *
 * @throws Exception
 */
public void testCRUD() throws Exception
{
    final String PATH1 = "FTPServerTest";
    final String PATH2 = "Second part";
    
    logger.debug("Start testFTPCRUD");
    
    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 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
        ftp.makeDirectory(PATH1);
        ftp.cwd(PATH1);
        
        // make sub-directory in new directory
        ftp.makeDirectory(PATH2);
        ftp.cwd(PATH2);
        
        // List the files in the new directory
        FTPFile[] files = ftp.listFiles();
        assertTrue("files not empty", files.length == 0);
        
        // Create a file
        String FILE1_CONTENT_1="test file 1 content";
        String FILE1_NAME = "testFile1.txt";
        ftp.appendFile(FILE1_NAME , new ByteArrayInputStream(FILE1_CONTENT_1.getBytes("UTF-8")));
        
        // Get the new file
        FTPFile[] files2 = ftp.listFiles();
        assertTrue("files not one", files2.length == 1);
        
        InputStream is = ftp.retrieveFileStream(FILE1_NAME);
        
        String content = inputStreamToString(is);
        assertEquals("Content is not as expected", content, FILE1_CONTENT_1);
        ftp.completePendingCommand();
        
        // Update the file contents
        String FILE1_CONTENT_2="That's how it is says Pooh!";
        ftp.storeFile(FILE1_NAME , new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8")));
        
        InputStream is2 = ftp.retrieveFileStream(FILE1_NAME);
        
        String content2 = inputStreamToString(is2);
        assertEquals("Content is not as expected", FILE1_CONTENT_2, content2);
        ftp.completePendingCommand();
        
        // now delete the file we have been using.
        assertTrue (ftp.deleteFile(FILE1_NAME));
        
        // negative test - file should have gone now.
        assertFalse (ftp.deleteFile(FILE1_NAME));
        
    } 
    finally
    {
        // clean up tree if left over from previous run

        ftp.disconnect();
    }    
}
 
Example 16
Source File: FtpService.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
@Override
public AnswerItem<AppService> getFTP(HashMap<String, String> informations, FTPClient ftp, AppService myResponse) throws IOException {
    MessageEvent message = null;
    AnswerItem<AppService> result = new AnswerItem<>();
    LOG.info("Start retrieving ftp file");
    FTPFile[] ftpFile = ftp.listFiles(informations.get("path"));
    if (ftpFile.length != 0) {
        InputStream done = ftp.retrieveFileStream(informations.get("path"));
        boolean success = ftp.completePendingCommand();
        myResponse.setResponseHTTPCode(ftp.getReplyCode());
        if (success && FTPReply.isPositiveCompletion(myResponse.getResponseHTTPCode())) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int n = 0;
            while ((n = done.read(buf)) >= 0) {
                baos.write(buf, 0, n);
            }
            byte[] content = baos.toByteArray();
            myResponse.setFile(content);
            LOG.info("ftp file successfully retrieve");
            message = new MessageEvent(MessageEventEnum.ACTION_SUCCESS_CALLSERVICE);
            message.setDescription(message.getDescription().replace("%SERVICEMETHOD%", "GET"));
            message.setDescription(message.getDescription().replace("%SERVICEPATH%", informations.get("path")));
            result.setResultMessage(message);
            String expectedContent = IOUtils.toString(new ByteArrayInputStream(content), "UTF-8");
            String extension = testCaseExecutionFileService.checkExtension(informations.get("path"), "");
            if ("JSON".equals(extension) || "XML".equals(extension) || "TXT".equals(extension)) {
                myResponse.setResponseHTTPBody(expectedContent);
            }
            myResponse.setResponseHTTPBodyContentType(extension);
            result.setItem(myResponse);
            baos.close();
        } else {
            LOG.error("Error when downloading the file. Something went wrong");
            message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
            message.setDescription(message.getDescription().replace("%SERVICE%", informations.get("path")));
            message.setDescription(message.getDescription().replace("%DESCRIPTION%",
                    "Error when downloading the file. Something went wrong"));
            result.setResultMessage(message);
        }
        done.close();
    } else {
        LOG.error("The file is not present on FTP server. Please check the FTP path");
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
        message.setDescription(message.getDescription().replace("%SERVICE%", informations.get("path")));
        message.setDescription(message.getDescription().replace("%DESCRIPTION%",
                "Impossible to retrieve the file. Please check the FTP path"));
        result.setResultMessage(message);
    }
    return result;
}
 
Example 17
Source File: FTPUtil.java    From seed with Apache License 2.0 4 votes vote down vote up
/**
 * 文件下载
 * <p>
 *     文件下载失败时,该方法会自动登出服务器并释放FTP连接,然后抛出RuntimeException
 *     读取文件流后,一定要调用completePendingCommand()告诉FTP传输完毕,否则会导致该FTP连接在下一次读取不到文件
 * </p>
 * @param hostname  目标主机地址
 * @param username  FTP登录用户
 * @param password  FTP登录密码
 * @param remoteURL 保存在FTP上的含完整路径和后缀的完整文件名
 */
public static InputStream download(String hostname, String username, String password, String remoteURL){
    if(!login(hostname, username, password, DEFAULT_DEFAULT_TIMEOUT, DEFAULT_CONNECT_TIMEOUT, DEFAULT_DATA_TIMEOUT)){
        throw new SeedException(CodeEnum.SYSTEM_BUSY.getCode(), "FTP服务器登录失败");
    }
    FTPClient ftpClient = ftpClientMap.get();
    try{
        //注意这里没有写成new String(remoteURL.getBytes(DEFAULT_CHARSET), "ISO-8859-1")
        //这是因为有时会因为编码的问题导致明明ftp上面有文件,但读到的是空数组,所以我们就使用默认编码
        FTPFile[] files = ftpClient.listFiles(new String(remoteURL.getBytes(DEFAULT_CHARSET)));
        if(1 != files.length){
            logout();
            throw new SeedException(CodeEnum.FILE_NOT_FOUND.getCode(), "远程文件["+remoteURL+"]不存在");
        }
        InputStream is = ftpClient.retrieveFileStream(remoteURL);
        //拷貝InputStream
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len;
        while((len=is.read(buff)) > -1){
            baos.write(buff, 0, len);
        }
        baos.flush();
        //事实上就像JDK的API所述:Closing a ByteArrayOutputStream has no effect
        //查询ByteArrayOutputStream.close()的源码会发现,它没有做任何事情,所以其close()与否是无所谓的
        baos.close();
        IOUtils.closeQuietly(is);
        //completePendingCommand()會一直等待FTPServer返回[226 Transfer complete]
        //但是FTPServer需要在InputStream.close()執行之後才會返回,所以要先執行InputStream.close()
        //201704121637測試發現:對於小文件,沒有調用close(),直接completePendingCommand()也會返回true
        //但大文件就會卡在completePendingCommand()位置,所以上面做了一步InputStream拷貝
        if(!ftpClient.completePendingCommand()){
            logout();
            throw new SeedException(CodeEnum.SYSTEM_BUSY.getCode(), "File transfer failed.");
        }
        return new ByteArrayInputStream(baos.toByteArray());
    }catch(IOException e){
        logout();
        throw new SeedException(CodeEnum.SYSTEM_BUSY.getCode(), "从FTP服务器["+hostname+"]下载文件["+remoteURL+"]失败,堆棧軌跡如下:", e);
    }
}
 
Example 18
Source File: FTPClientTemplate.java    From MicroCommunity with Apache License 2.0 4 votes vote down vote up
/**  
     * 上传文件到FTP服务器,支持断点续传  
     *  localAbsoluteFile 本地文件名称,绝对路径
     *  remoteAbsoluteFile 远程文件路径,使用/home/directory1/subdirectory/file.ext或是 http://www.guihua.org /subdirectory/file.ext
     * 							按照Linux上的路径指定方式,支持多级目录嵌套,支持递归创建不存在的目录结构
     * @return 上传结果
     * @throws IOException
     */  
    public Map upload() throws Exception {
    	FTPClient ftpClient =null;
    	Map result=new HashMap();

    	String flag="1";
        try {
        	ftpClient =getFTPClient();
            File f = new File(localfilename);
            long localSize = f.length();  
            threadpara.put("filesize", localSize);
            //对远程目录的处理   
            if(serverfilename.contains("/")){   
                //创建服务器远程目录结构,创建失败直接返回   
                if(!mkdirMore(serverfilename.substring(0,serverfilename.lastIndexOf("/")+1))){  
                	threadpara.put("flag","0");
                	return threadpara;
                }   
            }   
            //检查远程是否存在文件   
            FTPFile[] files = ftpClient.listFiles(new String(serverfilename.getBytes("GBK"),"iso-8859-1"));
            if(files.length == 1){   
                long remoteSize = files[0].getSize();   
                if(remoteSize>=localSize){
                	threadpara.put("flag","1");
                	return threadpara;
                }
                //尝试移动文件内读取指针,实现断点续传   
                result = uploadFile(serverfilename, f,remoteSize);   
                   
                //如果断点续传没有成功,则删除服务器上文件,重新上传   
                if("0".equals(result.get("flag").toString())){   
                    if(!ftpClient.deleteFile(serverfilename)){   
                        return result;   
                    }   
                    result = uploadFile(serverfilename, f,  0);   
                }   
            }else {   
                result = uploadFile(serverfilename, new File(localfilename),  0);
            }   
        } catch (Exception e1) {
//        	result=result;
			// TODO Auto-generated catch block
			//e1.printStackTrace();
			throw e1;
		}
        threadpara.put("flag",result.get("flag"));
    	return threadpara;
    }
 
Example 19
Source File: FtpCheck.java    From commons-vfs with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) throws Exception {
    if (args.length < 3) {
        throw new IllegalArgumentException("Usage: FtpCheck user pass host dir");
    }
    final String user = args[0];
    final String pass = args[1];
    final String host = args[2];
    String dir = null;
    if (args.length == 4) {
        dir = args[3];
    }

    final FTPClient client = new FTPClient();
    client.connect(host);
    final int reply = client.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        throw new IllegalArgumentException("cant connect: " + reply);
    }
    if (!client.login(user, pass)) {
        throw new IllegalArgumentException("login failed");
    }
    client.enterLocalPassiveMode();

    final OutputStream os = client.storeFileStream(dir + "/test.txt");
    if (os == null) {
        throw new IllegalStateException(client.getReplyString());
    }
    os.write("test".getBytes(Charset.defaultCharset()));
    os.close();
    client.completePendingCommand();

    if (dir != null && !client.changeWorkingDirectory(dir)) {
        throw new IllegalArgumentException("change dir to '" + dir + "' failed");
    }

    System.err.println("System: " + client.getSystemType());

    final FTPFile[] files = client.listFiles();
    for (int i = 0; i < files.length; i++) {
        final FTPFile file = files[i];
        if (file == null) {
            System.err.println("#" + i + ": " + null);
        } else {
            System.err.println("#" + i + ": " + file.getRawListing());
            System.err.println("#" + i + ": " + file.toString());
            System.err.println("\t name:" + file.getName() + " type:" + file.getType());
        }
    }
    client.disconnect();
}
 
Example 20
Source File: FTPService.java    From cs-actions with Apache License 2.0 4 votes vote down vote up
private boolean remoteFileExists(FTPClient ftpClient, String filePath) throws IOException {
    return ftpClient.listFiles(filePath).length != 0;
}