Ftp二进制下载

package com.mcm.socket.ftp;

import java.io.*;
import sun.net.*;
import sun.net.ftp.*;

public class FtpUtil {
	private String ip="";
	private String username="";
	private String password="";
	private int port=21;
	private String path="";
	FtpClient ftpClient=null;
	OutputStream os=null;
	FileInputStream is=null;
	
	public FtpUtil(String serverIP,String username,String password){
		this.ip=serverIP;
		this.username=username;
		this.password=password;
	}
	
	public FtpUtil(String serverIP,String username,String password,int port){
		this.ip=serverIP;
		this.username=username;
		this.password=password;
		this.port=port;
	}
	/**
	 * 连接FTP并登录
	 * @return 
	 */
	public boolean connectServer(){
		ftpClient=new FtpClient();
		try {
			if(this.port!=-1){
				ftpClient.openServer(this.ip,this.port);
			}else{
				ftpClient.openServer(this.ip);
			}
			ftpClient.login(this.username, this.password);
			if(this.path.length()!=0){
				ftpClient.cd(this.path);//path是ftp下的主目录的子目录
			}
			ftpClient.binary();//用二进制上传下载
			System.out.println("已登录到\""+ftpClient.pwd()+"\"目录!! ");
			return  true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
	/**
	 * 从服务器断开
	 * @return 
	 */
	public boolean closeServer(){
		try {
			if(is!=null){
				is.close();
			}
			if(os!=null){
				os.close();
			}
			if(ftpClient!=null){
				ftpClient.closeServer();
			}
			System.out.println("已从服务器断开");
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
	/**
	 * 检查文件夹在当前目录下是否存在
	 * @param dir 纯英文操作不支持中文
	 * @return 
	 */
	public boolean isDirExist(String dir){
		String pwd="";
		try {
			pwd=ftpClient.pwd();
			ftpClient.cd(dir);
			ftpClient.cd(pwd);
		} catch (Exception e) {
			return false;
		}
		return true;
	}
	public long downloadFile(String filename,String newfilename){
		long result=0;
		TelnetInputStream is=null;
		FileOutputStream os=null;
		try{
			is=ftpClient.get(filename);
			File outFile=new File(newfilename);
			os=new FileOutputStream(outFile);
			byte[] bytes=new byte[1024];
			int c;
			while((c=is.read(bytes))!=-1){
				os.write(bytes,0,c);
				result=result+c;
			}
		}catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(is!=null){
					is.close();
				}
				if(os!=null){
					os.close();
				}
			} catch (IOException e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}
	
	public static void main(String[] args) {
		
		
	}

}

你可能感兴趣的:(java,ftp,二进制下载文件)