apache.ftp

package ftp.apache.ftp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import ftp.FtpUser;

/**
 */
public class FtpApache {
    private FTPClient ftpClient = null;
    public boolean loginFtp(FtpUser ftpUser) throws SocketException,
	    IOException {
	ftpClient = new FTPClient();
	ftpClient.connect(ftpUser.getIp());
	boolean success = ftpClient.login(ftpUser.getUserName(),
		ftpUser.getPassWord());
	if (success) {
	    System.out.println("ftp登录成功");
	    // 改变目录
	    if (changeFtpPath()) {
		return true;
	    }
	    System.out.println("ftp目录改变失败");
	    return false;
	}
	return false;
    }

    public boolean changeFtpPath() {

	try {
	    if (ftpClient.changeWorkingDirectory("/")) {
		return true;
	    }
	} catch (IOException e) {
	    System.out.println("改变当前的ftp目录 失败");
	    e.printStackTrace();
	}
	return false;

    }

    public void getFtpFileList(String ftpBookPath) {
	/** 获得目录下的所有目录 */
	FTPFile[] ftpFileList = null;
	try {
	    ftpFileList = ftpClient.listFiles(ftpBookPath);
	    /** 循环遍历 */
	    for (int i = 0; i < ftpFileList.length; i++) {
		/** ftpFile对象 */
		FTPFile ftpFile = ftpFileList[i];

		/** ftpFile 名称 */
		String fileName = ftpFile.getName();

		/** 路径名称 */
		String clientMEB = ftpBookPath + fileName;

		if (ftpFile.isFile()) {
		    System.out.println("文件路径:" + clientMEB);
		    continue;
		}
	    }
	} catch (IOException e) {
	    System.out.println("目录不存在");
	    e.printStackTrace();
	}
    }

    public boolean downloadMEB(String path) {
	OutputStream iStream = null;
	try {
	    /** 设置以二进制方式传输 */
	    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
	    // 文件名
	    File f = new File("c:\\test4ffffffffffffffffff344.lst");
	    iStream = new FileOutputStream(f);
	    boolean flow = ftpClient.retrieveFile(path, iStream);
	    if (!flow) {
		System.out.println("ftp流 不存在");
	    }
	} catch (Exception e) {

	    e.printStackTrace();
	    return false;
	} finally {
	    /** 断开 ftpClient */
	    ftpClientClose();
	}
	return true;
    }

    /**
     * 断开 ftpClient
     */
    private void ftpClientClose() {
	if (ftpClient.isConnected()) {
	    try {
		ftpClient.disconnect();
		System.out.println("ftp断开");
	    } catch (IOException e) {
		System.out.println("ftp关闭失败");
		e.printStackTrace();
	    }
	}
    }
}

你可能感兴趣的:(java,apache,c,.net,F#)