Java Code Examples for org.apache.commons.net.ftp.FTPClient#deleteFile()

The following examples show how to use org.apache.commons.net.ftp.FTPClient#deleteFile() . 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: ImgServiceImpl.java    From Tbed with GNU Affero General Public License v3.0 6 votes vote down vote up
public void delectFTP(Keys key, String fileName) {
    FTPClient ftp = new FTPClient();
    String[] host = key.getEndpoint().split("\\:");
    String h = host[0];
    Integer p = Integer.parseInt(host[1]);
    try {
        if(!ftp.isConnected()){
            ftp.connect(h,p);
        }
        ftp.login(key.getAccessKey(), key.getAccessSecret());
        ftp.deleteFile(fileName);
    } catch (IOException e) {
        e.printStackTrace();
        Print.warning("删除FTP存储的图片失败");
    }
}
 
Example 3
Source File: FTPClientTemplate.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/** 
 * 批量删除 
 *  
 * @param delFiles 
 * @param autoClose 是否自动关闭当前连接 
 *  
 * @return 
 * @throws Exception
 */  
public boolean delete(String[] delFiles, boolean autoClose) throws Exception {
    try {  
        FTPClient ftpClient = getFTPClient();
        for (String s : delFiles) {
            ftpClient.deleteFile(s);  
        }  
        return true;  
    } catch (IOException e) {
        throw new Exception("Couldn't delete file from server.", e);
    } finally {  
        if (autoClose) {  
            disconnect(); //关闭链接  
        }  
    }  
}
 
Example 4
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 boolean delete(FTPClient client, Path file, boolean recursive)
    throws IOException {
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  String pathName = absolute.toUri().getPath();
  try {
    FileStatus fileStat = getFileStatus(client, absolute);
    if (fileStat.isFile()) {
      return client.deleteFile(pathName);
    }
  } catch (FileNotFoundException e) {
    //the file is not there
    return false;
  }
  FileStatus[] dirEntries = listStatus(client, absolute);
  if (dirEntries != null && dirEntries.length > 0 && !(recursive)) {
    throw new IOException("Directory: " + file + " is not empty.");
  }
  for (FileStatus dirEntry : dirEntries) {
    delete(client, new Path(absolute, dirEntry.getPath()), recursive);
  }
  return client.removeDirectory(pathName);
}
 
Example 5
Source File: FTPFileSystem.java    From big-c 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 boolean delete(FTPClient client, Path file, boolean recursive)
    throws IOException {
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  String pathName = absolute.toUri().getPath();
  try {
    FileStatus fileStat = getFileStatus(client, absolute);
    if (fileStat.isFile()) {
      return client.deleteFile(pathName);
    }
  } catch (FileNotFoundException e) {
    //the file is not there
    return false;
  }
  FileStatus[] dirEntries = listStatus(client, absolute);
  if (dirEntries != null && dirEntries.length > 0 && !(recursive)) {
    throw new IOException("Directory: " + file + " is not empty.");
  }
  for (FileStatus dirEntry : dirEntries) {
    delete(client, new Path(absolute, dirEntry.getPath()), recursive);
  }
  return client.removeDirectory(pathName);
}
 
Example 6
Source File: FTPOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
private boolean delete(FTPClient ftp, Info info, DeleteParameters params) throws IOException {
	if (Thread.currentThread().isInterrupted()) {
		throw new IOException(FileOperationMessages.getString("IOperationHandler.interrupted")); //$NON-NLS-1$
	}
	URI uri = info.getURI();
	if (info.isDirectory()) {
		if (params.isRecursive()) {
			List<Info> children = list(uri, ftp, LIST_NONRECURSIVE);
			for (Info child: children) {
				delete(ftp, child, params);
			}
			return ftp.removeDirectory(getPath(uri));
		} else {
			throw new IOException(MessageFormat.format(FileOperationMessages.getString("IOperationHandler.cannot_remove_directory"), uri)); //$NON-NLS-1$
		}
	} else {
		return ftp.deleteFile(getPath(uri));
	}
}
 
Example 7
Source File: PooledFTPOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
private boolean delete(FTPClient ftp, Info info, DeleteParameters params) throws IOException {
	if (Thread.currentThread().isInterrupted()) {
		throw new IOException(FileOperationMessages.getString("IOperationHandler.interrupted")); //$NON-NLS-1$
	}
	URI uri = info.getURI();
	if (info.isDirectory()) {
		if (params.isRecursive()) {
			List<Info> children = list(uri, ftp, LIST_NONRECURSIVE);
			for (Info child: children) {
				delete(ftp, child, params);
			}
			return ftp.removeDirectory(getPath(uri));
		} else {
			throw new IOException(MessageFormat.format(FileOperationMessages.getString("IOperationHandler.cannot_remove_directory"), uri)); //$NON-NLS-1$
		}
	} else {
		return ftp.deleteFile(getPath(uri));
	}
}
 
Example 8
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 boolean delete(FTPClient client, Path file, boolean recursive)
    throws IOException {
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  String pathName = absolute.toUri().getPath();
  FileStatus fileStat = getFileStatus(client, absolute);
  if (!fileStat.isDir()) {
    return client.deleteFile(pathName);
  }
  FileStatus[] dirEntries = listStatus(client, absolute);
  if (dirEntries != null && dirEntries.length > 0 && !(recursive)) {
    throw new IOException("Directory: " + file + " is not empty.");
  }
  if (dirEntries != null) {
    for (int i = 0; i < dirEntries.length; i++) {
      delete(client, new Path(absolute, dirEntries[i].getPath()), recursive);
    }
  }
  return client.removeDirectory(pathName);
}
 
Example 9
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 boolean delete(FTPClient client, Path file, boolean recursive)
    throws IOException {
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  String pathName = absolute.toUri().getPath();
  FileStatus fileStat = getFileStatus(client, absolute);
  if (!fileStat.isDir()) {
    return client.deleteFile(pathName);
  }
  FileStatus[] dirEntries = listStatus(client, absolute);
  if (dirEntries != null && dirEntries.length > 0 && !(recursive)) {
    throw new IOException("Directory: " + file + " is not empty.");
  }
  if (dirEntries != null) {
    for (int i = 0; i < dirEntries.length; i++) {
      delete(client, new Path(absolute, dirEntries[i].getPath()), recursive);
    }
  }
  return client.removeDirectory(pathName);
}
 
Example 10
Source File: FTPTransfer.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteFile(final String path, final String remoteFileName) throws IOException {
    final FTPClient client = getClient(null);
    if (path != null) {
        setWorkingDirectory(path);
    }
    if (!client.deleteFile(remoteFileName)) {
        throw new IOException("Failed to remove file " + remoteFileName + " due to " + client.getReplyString());
    }
}
 
Example 11
Source File: FTPClientUtils.java    From springboot-ureport with Apache License 2.0 5 votes vote down vote up
/**
 * FTP删除文件
 */
public boolean delete(String path) {
	FTPClient ftpClient = borrowObject();
	try {
		boolean result = ftpClient.deleteFile(path);
		return result;
	} catch (IOException e) {
		e.printStackTrace();
		throw new RuntimeException(e);
	}finally {
		returnObject(ftpClient);
	}
}
 
Example 12
Source File: FtpServiceImp.java    From imageServer with Apache License 2.0 5 votes vote down vote up
/**
 * 删除FTP服务器上的指定文件
 *
 * @param directory 文件目录
 * @param fileName  文件名
 * @return true : 删除成功
 * @throws IOException 删除失败
 */
synchronized public boolean deleteFile(String directory, String fileName) throws IOException {
    log.info("删除FTP文件");
    log.info("被删除的文件目录:" + directory);
    log.info("被删除的文件:" + fileName);
    FTPClient ftpClient = FTPUtil.getFTPClient(ftpConnectAttr);
    boolean result = ftpClient != null && ftpClient.deleteFile(directory + "/" + fileName);
    if(result && ftpClient.isConnected())
        ftpClient.disconnect();
    return result;
}
 
Example 13
Source File: FtpServiceImp.java    From imageServer with Apache License 2.0 5 votes vote down vote up
/**
 * 删除FTP服务器上的指定文件
 *
 * @param filePath 被删除文件在FTP服务器上的全路径
 * @return true : 删除成功
 * @throws IOException 删除失败
 */
@Override
synchronized public boolean deleteFile(String filePath) throws IOException {
    FTPClient ftpClient = FTPUtil.getFTPClient(ftpConnectAttr);
    boolean result = ftpClient != null && ftpClient.deleteFile(filePath);
    if(result && ftpClient.isConnected())
        ftpClient.disconnect();
    return result;
}
 
Example 14
Source File: FTPTransfer.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteFile(final FlowFile flowFile, final String path, final String remoteFileName) throws IOException {
    final FTPClient client = getClient(flowFile);
    if (path != null) {
        setWorkingDirectory(path);
    }
    if (!client.deleteFile(remoteFileName)) {
        throw new IOException("Failed to remove file " + remoteFileName + " due to " + client.getReplyString());
    }
}
 
Example 15
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 16
Source File: FTPServerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * 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();
        }
    }       

}