FTPClientUtils.java 3.08 KB
package com.bsth.util;

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

import org.apache.commons.net.ftp.FTPClient;
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.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;
	}
	
	// 将本地文件上传到FTP服务器上
	public void testUpLoadFromDisk(){
		
		 try { 
		        FileInputStream in=new FileInputStream(new File("D:/test.txt")); 
		        
		        boolean flag = uploadFile("192.168.168.101", 21, "testftpservice", "123", "C:/ftptest", "test.txt", in); 
		        
		        System.out.println(flag); 
		        
		    } 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"));
			
			 boolean flag = uploadFile("192.168.168.101", 21, "testftpservice", "123", "C:/ftptest", "test.txt", input); 
			
			System.out.println(flag);
			
		} catch (UnsupportedEncodingException e) {
			
			e.printStackTrace();
			
		}
		
	}
	
	public static void main(String[] args){
		
		FTPClientUtils testFClient = new FTPClientUtils();
		
		System.out.println(4.18f+ 1.35f);

		
		// testFClient.testUpLoadFromString();
		
	}
	
}