用Java實現FTP服務器上傳下載

一、帶入ftp客戶端相關的jar

<!-- ftp連接start -->
    <dependency>
        <groupId>commons-net</groupId>
        <artifactId>commons-net</artifactId>
        <version>3.5</version>
    </dependency>
<!-- ftp連接end-->

二、新建FTPClient客戶端

public static FTPClient init(){
        FTPClient ftpClient = new FTPClient();
        try {
            // 連接FTP服務器
            ftpClient.connect(HOSTNAME, PORT);
            //獲取服務器返回碼
            int reply = ftpClient.getReplyCode();
            //驗證服務器是否連接成功
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                logger.error("FTPServer 拒絕連接");
                return null;
            }
            // 登錄FTP服務器
            boolean result =ftpClient.login(USERNAME, PASSWORD);

            //驗收是否登錄成功
            if (!result) {
                logger.error("ftpClient登陸失敗!");
                throw new Exception("ftpClient登陸失敗! userName:"+ USERNAME + " ; password:"
                        + PASSWORD);
            }
            //設置傳輸的編碼格式
            ftpClient.setControlEncoding("UTF-8");
            //設置文件類型(這個採用二進制格式)
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //設置爲主動模式(pass)
            ftpClient.enterLocalPassiveMode();
            //創建目錄
            ftpClient.makeDirectory(PATHNAME);
            //切換到新建的目錄
            ftpClient.changeWorkingDirectory(PATHNAME);
        }catch (Exception e) {
            logger.equals(e);
        }
        return ftpClient;
    }

三、上傳文件

ftpClient.storeFile(fileName , inputStream);

其中fileName是保存在ftp中的文件名,inputString爲文件的內容;

四、下載文件
列出ftp當前目錄下的所有文件,如果文件名相同,則保存文件到本地

FTPFile[] ftpFiles = ftpClient.listFiles();
FTPFile file=ftpFiles[0];
OutputStream os = new FileOutputStream(localFile);
ftpClient.retrieveFile(file.getName(), os);

其中localFile爲本地的文件路徑,file位ftp服務器的文件

五、刪除文件

ftpClient.dele(pathname);

pathname爲ftp服務器文件路徑

六、刪除文件夾與文件夾下面的所有子文件和文件夾
列出所有文件和文件夾,然後用遍歷刪除所有文件
FTPFile[] files = ftpClient.listFiles(ftpPath);
刪除文件夾
flag = ftpClient.removeDirectory(ftpPath);

7、代碼如下:

mport java.io.File;
import java.io.FileInputStream;
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.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eakom.common.util.ftpPool.FTPClientFactory;


public class TestFTPClient {
    private static Logger logger = LoggerFactory.getLogger(TestFTPClient.class);
    /**FTP服務器的IP地址*/
    private static final String HOSTNAME="192.168.158.98";
    /**FTP服務器的端口*/
    private static final int PORT=21;
    /**FTP服務器的登錄名*/
    private static final String USERNAME="ftpadmin";
    /**FTP服務器的密碼*/
    private static final String PASSWORD="eakom123456";
    /**FTP服務器的操作路徑*/
    private static final String PATHNAME="/home/ftpadmin/aa";

    public static void main(String[] args) throws UnsupportedEncodingException {
        InputStream inputStream = null;
        try {
            String path="C:/Users/Administrator/Desktop/44/中文.txt";
            File file = new File(path);
            inputStream = new FileInputStream(file);
            FTPClient ftpClient=init();
            String fileName = file.getName();
            boolean flag = ftpClient.storeFile(new String(fileName.getBytes("GBK"), "iso-8859-1") , inputStream);
            System.out.println(flag);
        } catch (IOException e) {
            logger.error("上傳失敗",e);
        }
    }
    /**
     * 上傳文件
     * @param ftpClient
     * @throws IOException 
     */
    public void upload(FTPClient ftpClient) throws IOException{
        InputStream inputStream = null;
        try {
            String path="C:/Users/Administrator/Desktop/44/中文.txt";
            File file = new File(path);
            inputStream = new FileInputStream(file);
            String fileName = file.getName();
            boolean flag = ftpClient.storeFile(new String(fileName.getBytes("GBK"), "iso-8859-1") , inputStream);   
            ftpClient.logout();
        } catch (IOException e) {
            logger.error("上傳失敗",e);
        }
    }
    /**
     * 下載文件
     * @param ftpClient
     * @param filename  下載的文件名
     * @throws IOException
     */
    public void download(FTPClient ftpClient,String filename) throws IOException{
        FTPFile[] ftpFiles = ftpClient.listFiles();
        for (FTPFile file : ftpFiles) {
            if (filename.equalsIgnoreCase(file.getName())) {
                File localFile = new File("C:/Users/Administrator/Desktop" + "/" + file.getName());
                OutputStream os = new FileOutputStream(localFile);
                ftpClient.retrieveFile(file.getName(), os);
                os.close();
            }
        }
        ftpClient.logout();
    }
    /**
     * 
     * @param ftpClient
     * @param pathname 文件路徑名
     * @throws IOException
     */
    public void deleteFile(FTPClient ftpClient,String pathname) throws IOException{
        ftpClient.dele(pathname);
        ftpClient.logout();
    }

    public static FTPClient init(){
        FTPClient ftpClient = new FTPClient();
        try {
            // 連接FTP服務器
            ftpClient.connect(HOSTNAME, PORT);
            //獲取服務器返回碼
            int reply = ftpClient.getReplyCode();
            //驗證服務器是否連接成功
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                logger.error("FTPServer 拒絕連接");
                return null;
            }
            // 登錄FTP服務器
            boolean result =ftpClient.login(USERNAME, PASSWORD);

            //驗收是否登錄成功
            if (!result) {
                logger.error("ftpClient登陸失敗!");
                throw new Exception("ftpClient登陸失敗! userName:"+ USERNAME + " ; password:"
                        + PASSWORD);
            }
            //設置傳輸的編碼格式
            ftpClient.setControlEncoding("UTF-8");
            //設置文件類型(這個採用二進制格式)
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //設置爲主動模式(pass)
            ftpClient.enterLocalPassiveMode();
            //創建目錄
            ftpClient.makeDirectory(PATHNAME);
            //切換到新建的目錄
            ftpClient.changeWorkingDirectory(PATHNAME);
        }catch (Exception e) {
            logger.equals(e);
        }
        return ftpClient;
    }
    /**
     * 刪除文件夾與文件夾下面的所有子文件和文件夾
     * @param ftpClient
     * @param ftpPath
     * @return
     * @throws IOException
     */
    private static boolean DeleteDir(FTPClient ftpClient, String ftpPath)
            throws IOException {
        FTPFile[] files = ftpClient.listFiles(ftpPath);
        boolean flag = false;
        for (FTPFile f : files) {
            String path = ftpPath + File.separator + f.getName();
            if (f.isFile()) {
                // 是文件就刪除文件
                ftpClient.deleteFile(path);
            } else if (f.isDirectory()) {
                if(f.getName()!=null&&!".".equals(f.getName())&&!"..".equals(f.getName())){
                    DeleteDir(ftpClient, path);
                }
            }
        }
        // 每次刪除文件夾以後就去查看該文件夾下面是否還有文件,沒有就刪除該空文件夾
        FTPFile[] files2 = ftpClient.listFiles(ftpPath);
        if (files2.length == 2) {
            flag = ftpClient.removeDirectory(ftpPath);
        } else {
            flag = false;
        }
        return flag;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章