java ftp 다운로드 도구 작성

자바에 ftp를 쓰는 도구가 필요합니다. 자바의 기초가 조금밖에 없기 때문입니다. 그러나 몇 년 동안 사용하지 않았기 때문에 거의 할 수 없습니다. 조금씩 할 수 밖에 없습니다. 주울 수 있어서 다행입니다.
그러나 Linux에서javac컴파일을 사용하기 때문에 WIN에서 IDE를 사용하여 이런 일을 하는 것이 아니기 때문에 실행과 컴파일에 시간이 좀 걸렸지만 바로 이렇게 JAVA의 컴파일, 실행에 대한 지식이 좀 더 이해되었기 때문이다.
ftp 다운로드 도구의 코드는 다음과 같습니다.

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.net.SocketException;  
import org.apache.commons.net.ftp.FTPClient;  
import org.apache.commons.net.ftp.FTPReply;  
public class FtpClient {
    private String         host;  
    private int            port;  
    private String         username;  
    private String         password;  
    private boolean        binaryTransfer = true;  
    private boolean        passiveMode    = true;  
    private String         encoding       = "UTF-8";  
    private int            clientTimeout  = 3000;  
    private boolean flag=true;
    private FTPClient ftpClient = null;
    public String getHost() {  
        return host;  
    }  
    public void setHost(String host) {  
        this.host = host;  
    }  
    public int getPort() {  
        return port;  
    }  
    public void setPort(int port) {  
        this.port = port;  
    }  
    public String getUsername() {  
        return username;  
    }  
    public void setUsername(String username) {  
        this.username = username;  
    }  
    public String getPassword() {  
        return password;  
    }  
    public void setPassword(String password) {  
        this.password = password;  
    }  
    public boolean isBinaryTransfer() {  
        return binaryTransfer;  
    }  
    public void setBinaryTransfer(boolean binaryTransfer) {  
        this.binaryTransfer = binaryTransfer;  
    }  
    public boolean isPassiveMode() {  
        return passiveMode;  
    }  
    public void setPassiveMode(boolean passiveMode) {  
        this.passiveMode = passiveMode;  
    }  
    public String getEncoding() {  
        return encoding;  
    }  
    public void setEncoding(String encoding) {  
        this.encoding = encoding;  
    }  
    public int getClientTimeout() {  
        return clientTimeout;  
    }  
    public void setClientTimeout(int clientTimeout) {  
        this.clientTimeout = clientTimeout;  
    }  
    public FtpClient(String Host) {
        this.username = "anonymous";
        this.encoding = "utf-8";
        this.binaryTransfer = true;
        this.binaryTransfer = true;
        this.port = 21;
        this.host = Host;
        try {
            this.ftpClient = getFTPClient();
        } catch (Exception e) {
            System.out.println("Create FTPClient error!");
        }
    }
    private FTPClient getFTPClient() throws IOException {  
        FTPClient ftpClient = new FTPClient();
        ftpClient.setControlEncoding(encoding);
        connect(ftpClient);
        if (passiveMode) {  
            ftpClient.enterLocalPassiveMode();  
        }  
        setFileType(ftpClient);
        try {  
            ftpClient.setSoTimeout(clientTimeout);  
        } catch (SocketException e) {  
            throw new IOException("Set timeout error.", e);  
        }  
        return ftpClient;  
    }  
    private void setFileType(FTPClient ftpClient) throws IOException {  
        try {  
            if (binaryTransfer) {  
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);  
            } else {  
                ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE);  
            }  
        } catch (IOException e) {  
            throw new IOException("Could not to set file type.", e);  
        }  
    }  
    public boolean connect(FTPClient ftpClient) throws IOException {  
        try {  
            ftpClient.connect(host, port);  
            int reply = ftpClient.getReplyCode();  
            if (FTPReply.isPositiveCompletion(reply)) {  
                if (ftpClient.login(username, password)) {  
                    setFileType(ftpClient);  
                    return true;  
                }  
            } else {  
                this.ftpClient.disconnect();  
                throw new IOException("FTP server refused connection.");  
            }  
        } catch (IOException e) {  
            if (this.ftpClient.isConnected()) {  
                try {  
                    this.ftpClient.disconnect();
                } catch (IOException e1) {  
                    throw new IOException("Could not disconnect from server.", e);  
                }  
            }  
            throw new IOException("Could not connect to server.", e);  
        }  
        return false;  
    }  
    private void disconnect() throws IOException {  
        try {  
            this.ftpClient.logout();  
        } catch (IOException e) {  
            System.out.println("logout may timeout!");
        } finally {
            if (this.ftpClient.isConnected()) {  
                this.ftpClient.disconnect();  
            }  
        } 
    }  
    public InputStream getStream(String serverFile) throws IOException {
        InputStream inStream = null;
        try {
            inStream = this.ftpClient.retrieveFileStream(serverFile);
            System.out.println("inStream get over!");
            return inStream;
        } catch (IOException e) {
            System.out.println("get stream exception");
            return null;
        }
    }
    public boolean writeStream(InputStream input, String localFile) throws IOException {
        FileOutputStream fout = new FileOutputStream(localFile);
        int ch = 0;
        if(input == null){
            System.out.println("input is null");
            return false;
        }
        try {
            ch = input.read();
            while(ch != -1){
                fout.write(ch);
                ch = input.read();
            }
            System.out.println("write over!");
            return flag;
        } catch (IOException e) {
            throw new IOException("Couldn't get file from server.", e);
        }
    }
    public boolean isExist(String remoteFilePath)throws IOException{
        try{
            File file=new File(remoteFilePath);
            String remotePath=remoteFilePath.substring(0,(remoteFilePath.indexOf(file.getName())-1));
            String[] listNames = this.ftpClient.listNames(remotePath);  
            System.out.println(remoteFilePath);
            for(int i=0;i<listNames.length;i++){
                System.out.println(listNames[i]);
                if(remoteFilePath.equals(listNames[i])){
                    flag=true;
                    System.out.println("file:"+file.getName()+" existed");
                    break;
                }else {
                    flag=false;
                }
            }
        } catch (IOException e) {  
            throw new IOException("FILE EXCEPTION", e);  
        }
        return flag;
    }
    //main for testing
    public static void main(String[] args) throws IOException {  
        String hostname = "cp01-testing-ps7130.cp01.baidu.com";
        String serverFile="/home/work/check_disk.sh";
        String localFile="/home/work/workspace/project/dhc2-0/dhc/base/ftp/task_get";
        FtpClient ftp = new FtpClient(hostname);  
        System.out.println(ftp.isExist(serverFile));
        ftp.writeStream(ftp.getStream(serverFile), localFile);
        ftp.disconnect();
    }  
}
이 도구는 다른 Hadoop 도구와 함께 그룹 업로드용으로 사용되기 때문에 input와 output를 분리하고 다른 도구를 편리하게 사용하기 위한 것입니다.
linux 설정에서 실행하는 방법을 추가합니다.
만약 이러한 코드가 linux 환경에서 실행되어야 한다면, 우선 응답하는 패키지를 설정해야 한다. 예를 들어

import org.apache.commons.net.ftp.FTPClient;
이 패키지는 아파치 사이트에서 직접 다운로드하면 됩니다. 압축을 풀고 대응하는jar 패키지를 찾아 컴파일할 때 인용합니다.

export FTPPATH="${ }/xxx.jar"
javac -classpath $CLASSPATH:$FTPPATH FtpClient.java
마찬가지로 실행할 때classpath를 지정해야 합니다.

java -classpath $CLASSPATH:$FTPPATH FtpClient
$FTPPATH를 CLASSPATH에 포함하지 말고 가방을 사용하려면 환경 변수를 인용하면 됩니다. 우리가 모든 가방을 import할 필요가 없는 것처럼 한꺼번에 추가할 필요가 없습니다.
위에서 말한 것이 바로 본문의 전체 내용입니다. 여러분들이 자바를 배우는 데 도움이 되었으면 합니다.
글을 친구에게 공유하거나 댓글을 남기는 데 시간이 좀 걸리세요.우리는 당신의 지지에 진심으로 감사할 것입니다.

좋은 웹페이지 즐겨찾기