FTPClientUtils.java 10.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
package com.bsth.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
/**
 * @Description: 向FTP服务器上传文件
 * 
 * @Version 1.0 2016-06-21 4:31:09 by 李强 
 * 
 */
public class FTPClientUtils {
	
	/** 
	 * @param  url FTP服务器hostname; 
	 * 
	 * - - - - port FTP服务器端口;
	 * 
	 * - - - - username FTP登录账号;
	 * 
	 * - - - - password FTP登录密码 ;
	 * 
	 * - - - - path FTP服务器保存目录;
	 * 
	 * - - - - filename 上传到FTP服务器上的文件名
	 * 
	 * - - - - input 输入流;
	 * 
	 * @return 成功返回true,否则返回false
	 * 
	 */
	public boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {
		
		boolean success = false;
		
		FTPClient ftp = new FTPClient();
		
		try {
			
			int reply;
			
			//连接FTP服务器,如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.connect(url, port);
			
			//登录
			ftp.login(username, password);
			
			reply = ftp.getReplyCode();
			
			if (!FTPReply.isPositiveCompletion(reply)) {
				
				ftp.disconnect();
				
				return success;
				
			}
			
			ftp.changeWorkingDirectory(path);
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftp.enterLocalPassiveMode();
			success = ftp.storeFile(new String(filename.getBytes("gbk"),"gbk"), input);
			/*success = ftp.storeFile(filename, input);	*/
			input.close();
			
			ftp.logout();
			
			// success = true;
			
		} catch (IOException e) {
			
			e.printStackTrace();
			
		} finally {
			
			if (ftp.isConnected()) {
				
				try {
					
					ftp.disconnect();
					
				} catch (IOException ioe) {
					
				}
				
			}
			
		}
		
		return success;
	}
	
	/**
	 * @Description : TOOD(将本地文件上传到FTP服务器上)
	 * 
	 * @param file
	 * 
	 * @param name
	 * 
	 * @param url
	 * 
	 * @param port
	 * 
	 * @param username
	 * 
	 * @param password
	 * 
	 * @param remotePath
	 * 
	 */
	public void FTPUpLoadFromDisk(File file,String name,String url, int port, String username, String password, String remotePath){
		
		 try { 
		        FileInputStream in=new FileInputStream(file); 
		        
		        boolean flag = uploadFile(url, port,username, password, remotePath, name, in);
		        
		      /* boolean flag = uploadFile("192.168.168.101", 21, "testftpservice", "123", "ftptest/", name, in);*/
		        
		       /* boolean flag = uploadFile("222.66.0.205", 21, "transport", "transport123", "ftptest/", name, in);*/
		        
		    } catch (FileNotFoundException e) { 
		    	
		        e.printStackTrace(); 
		        
		    } 
		
	}
	
	// 在FTP服务器上生成一个文件,并将一个字符串写入到该文件中
	public void testUpLoadFromString(){
		
		try {
			
			String str = "test ftp "+ "\r\n"+ "ccccc dddd";
			
			InputStream input = new ByteArrayInputStream(str.getBytes("utf-8"));
			
			uploadFile("192.168.168.101", 21, "testftpservice", "123", "ftptest/", "test.txt", input); 
			
		} catch (UnsupportedEncodingException e) {
			
			e.printStackTrace();
			
		}
		
	}
	
	/** 
     * @Description (删除FTP上的文件)
     * 
     * @param url FTP服务器IP地址 
     * 
     * @param port FTP服务器端口 
     * 
     * @param username FTP服务器登录名 
     * 
     * @param password FTP服务器密码 
     * 
     * @param remotePath 远程文件路径 
     * 
     * @param fileName 待删除的文件名 
     * 
     * @return boolean
     */  
    public static boolean deleteFtpFile(String url, int port, String username, String password, String remotePath, String fileName){  
    	
    	boolean success = false; 
    	
        FTPClient ftp = new FTPClient(); 
        
        try { 
        	
        	int reply;  
              
            // 连接FTP服务器  
            if (port > -1)
            	
            	ftp.connect(url, port);
                
            else  
            	
                ftp.connect(url);  
              
            // 登录  
            ftp.login(username, password);  
            
            reply = ftp.getReplyCode(); 
            
            if (!FTPReply.isPositiveCompletion(reply)) {
            	
            	ftp.disconnect(); 
            	
                return success;  
            }  
              
            // 转移到FTP服务器目录  
            
            ftp.changeWorkingDirectory(remotePath);
            
            /*success = ftp.deleteFile(fileName);*/
            
            success = ftp.deleteFile(new String(fileName.getBytes("gbk"),"gbk"));
            
            ftp.logout(); 
            
        } catch (IOException e){  
        	
        	e.printStackTrace();
        	
            success = false;
            
        } finally {
        	
        	if (ftp.isConnected()) {
        		
        		try { 
        			
                    ftp.disconnect();
                    
                } catch (IOException e) {  
                	
                	e.printStackTrace();
                	
                }  
            }  
        }  
        
        return success;  
    }  
	
    public static File GetFtpFile(String url, int port, String username, String password, String remotePath, String fileName){  
    	
        FTPClient ftp = new FTPClient(); 
       
        /*File destFile = new File(fileName); */
        
        File destFile = new File(fileName); 
        
        InputStream in = null; 
        
        OutputStream out = null; 
        
        try { 
        	
        	int reply;  
              
            // 连接FTP服务器  
            if (port > -1)
            	
            	ftp.connect(url, port);
                
            else  
            	
                ftp.connect(url);  
              
            // 登录  
            ftp.login(username, password);  
            
            reply = ftp.getReplyCode(); 
            
            if (!FTPReply.isPositiveCompletion(reply)) {
            	
            	ftp.disconnect(); 
            	
            }  
             
            // 转移到FTP服务器目录  
           
            ftp.changeWorkingDirectory(remotePath);
            
            ftp.enterLocalPassiveMode();
            
            FTPFile[] fs = ftp.listFiles();  
            
            System.out.println(fs.length);
            
          /*  for (FTPFile ff : fs) {  
                //解决中文乱码问题,两次解码  
                byte[] bytes=ff.getName().getBytes("gbk");  
                String fn=new String(bytes,"gbk");  
                if (fn.equals(fileName)) {  
                    //6.写操作,将其写入到本地文件中  
                    File localFile = new File(ff.getName());  
                    
                    
                    OutputStream is = new FileOutputStream(localFile);  
                    ftp.retrieveFile(ff.getName(), is);  
                    is.close();  
                }  
            } */
            
           /* File srcFile = new File(fileName);  */
            
           /* File srcFile = new File(new String(fileName.getBytes("gbk"),"gbk"));*/
            
            int byteread = 0; // 读取的字节数
           
           /* in =  ftp.retrieveFileStream(remotePath + fileName);*/
            
            in =  ftp.retrieveFileStream(new String(fileName.getBytes("gbk"),"gbk"));
         
            
            out = new FileOutputStream(destFile);
            
            byte[] buffer = new byte[1024];  
  
            while ((byteread = in.read(buffer)) != -1) { 
            	
                out.write(buffer, 0, byteread);  
                
            }  
            
            out.flush();
            ftp.logout(); 
            
        } catch (IOException e){  
        	
        	e.printStackTrace();
        	
        } finally {
        	
        	try { 
        		
                if (out != null) 
                	
                    out.close();
                
                if (in != null) 
                	
                    in.close();
                
            } catch (IOException e) { 
            	
                e.printStackTrace(); 
                
            }
        	
        	if (ftp.isConnected()) {
        		
        		try { 
        			
                    ftp.disconnect();
                    
                } catch (IOException e) {  
                	
                	e.printStackTrace();
                	
                }  
            }  
        }  
        
        return destFile;  
    }

	public static boolean deleteFileByPrefix(String prefix, String url, int port, String username, String password, String remotePath) {
		boolean flag = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			if (port > -1) {
				ftp.connect(url, port);
			} else {
				ftp.connect(url);
			}
			ftp.login(username, password);
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return flag;
			}
			ftp.enterLocalPassiveMode();
			ftp.changeWorkingDirectory(remotePath);
			for (FTPFile file : ftp.listFiles()) {
				if (file.getName().startsWith(prefix)) {
					ftp.deleteFile(file.getName());
				}
			}
			ftp.logout();
		} catch (IOException e){
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return flag;
	}
	
    
	public static void main(String[] args) {
		
//		FTPClientUtils clientUtils = new FTPClientUtils();
//
//		Test test= new Test();
//
//		File[] sources = new File[] {new File("E:/20079.txt")};
//
//		File target = new File("release_package.tar.gz");
//
//		File targetFile = test.pack(sources, target);
		  
	/*	clientUtils.testUpLoadFromDisk(targetFile,targetFile.getName());*/
		
		
		/** 删除文件 */
		/*boolean a =clientUtils.deleteFtpFile("192.168.168.101", 21, "testftpservice", "123", "ftptest/", "release_package.tar.gz");*/
		FTPClientUtils.deleteFileByPrefix("100", "61.169.120.202", 10021, "ftpadmin", "ftp@123", "/transport/down/voice/");
	}
}