VietTuts

Tự Học Lập Trình Online

  • Home
  • Java
  • Servlet
  • JSP
  • Struts2
  • Hibernate
  • Spring
  • MyBatis
  • Java WS
  • C
  • C++
  • C#
  • Python
  • PHP
  • Excel
  • VBA
  • Web
    • JavaScript
    • JQUERY
    • JSON
    • AJAX
    • CSS
    • HTML
    • HTML5
    • Node.js
    • Angular 7
  • SQL
    • MySQL
    • SQL Server
  • Misc
    • Eclipse
    • Phần mềm tiện ích
    • Cấu trúc DL&GT
    • Selenium Test
Java Cơ Bản Các Khái Niệm Java OOPs Java String

Giao Thức TCP

Giao thức TCP/IP là gì? TCP/IP transfer file example

Giáo Thức UDP

Giao thức UDP là gì? UDP transfer file example

Giao Thức FTP

FTP là gì? Cài đặt FTP Server trên Window Connect FTP Server trong java Get list file from FTP Server Download file from FTP Server
Các Lớp Lồng Nhau Đa Luồng (Multithreading) Java AWT Java Swing Java I/O Java Date Chuyển Đối Kiểu Dữ Liệu Java Collections Java JDBC Các Tính Năng Mới Trong Java Bài Tập Java Có Lời Giải Câu Hỏi Phỏng Vấn Java

Download file from FTP Server


Java là gì? Học java core
Lập trình hướng đối tượng(OOPs) trong java

Lớp FTPClient (org.apache.commons.net.ftp.FTPClient) của thư viện commons-net-3.3.jar cung cấp các API cần thiết để làm việc với một máy chủ thông qua giao thức FTP.

Phương thức FTPClient.retrieveFile() được sử dụng để download file from FTP Server.

Nội dung chính

  • Dưới đây là ví dụ về download file from FTP Server

Dưới đây là ví dụ về download file from FTP Server

Giả sử ta có list file và folder trong path="/demo" trên FTP Server như sau:

get list file from ftp server

Chương trình sau sẽ download tất cả các file có phần mở rộng là ".jar" có trong path="/demo" trên FTP Server:

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPFileFilter;
import org.apache.commons.net.ftp.FTPReply;

public class FTPExample {
    private static final String FTP_SERVER_ADDRESS = "127.0.0.1";
    private static final int FTP_SERVER_PORT_NUMBER = 21;
    private static final int FTP_TIMEOUT = 60000;
    private static final int BUFFER_SIZE = 1024 * 1024 * 1;
    private static final String FTP_USERNAME = "haophong";
    private static final String FTP_PASSWORD = "1234567890";
    private static final String SLASH = "/";
    private FTPClient ftpClient;

    /**
     * main
     * 
     * @param args
     */
    public static void main(String[] args) {
        String ftpFolder = "/demo";
        String downloadFolder = "E:/ftpclient";
        String extJarFile = "jar";
        FTPExample ftpExample = new FTPExample();
        // get list file ends with (.jar) from ftp server
        List<FTPFile> listFiles = 
                ftpExample.getListFileFromFTPServer(ftpFolder, extJarFile);
        // download list file from ftp server and save to "E:/ftpclient"
        for (FTPFile ftpFile : listFiles) {
            ftpExample.downloadFTPFile(ftpFolder + SLASH + ftpFile.getName(),
                    downloadFolder + SLASH + ftpFile.getName());
        }
    }

    /**
     * using method retrieveFile(String, OutputStream) 
     * to download file from FTP Server
     * 
     * @author viettuts.vn
     * @param ftpFilePath
     * @param downloadFilePath
     */
    private void downloadFTPFile(String ftpFilePath, String downloadFilePath) {
        System.out.println("File " + ftpFilePath + " is downloading...");
        OutputStream outputStream = null;
        boolean success = false;
        try {
            File downloadFile = new File(downloadFilePath);
            outputStream = new BufferedOutputStream(
                    new FileOutputStream(downloadFile));
            // download file from FTP Server
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.setBufferSize(BUFFER_SIZE);
            success = ftpClient.retrieveFile(ftpFilePath, outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (success) {
            System.out.println("File " + ftpFilePath 
                    + " has been downloaded successfully.");
        }
    }

    /**
     * get list from ftp server
     * 
     * @author viettuts.vn
     * @param path
     * @return List<FTPFile>
     */
    private List<FTPFile> getListFileFromFTPServer(String path, final String ext) {
        List<FTPFile> listFiles = new ArrayList<FTPFile>();
        // connect ftp server
        connectFTPServer();
        try {
            // list file ends with "jar"
            FTPFile[] ftpFiles = ftpClient.listFiles(path, new FTPFileFilter() {
                public boolean accept(FTPFile file) {
                    return file.getName().endsWith(ext);
                }
            });
            if (ftpFiles.length > 0) {
                for (FTPFile ftpFile : ftpFiles) {
                    // add file to listFiles
                    if (ftpFile.isFile()) {
                        listFiles.add(ftpFile);
                    }
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return listFiles;
    }

    /**
     * connect ftp server
     * 
     * @author viettuts.vn
     */
    private void connectFTPServer() {
        ftpClient = new FTPClient();
        try {
            System.out.println("connecting ftp server...");
            // connect to ftp server
            ftpClient.setDefaultTimeout(FTP_TIMEOUT);
            ftpClient.connect(FTP_SERVER_ADDRESS, FTP_SERVER_PORT_NUMBER);
            // run the passive mode command
            ftpClient.enterLocalPassiveMode();
            // check reply code
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                disconnectFTPServer();
                throw new IOException("FTP server not respond!");
            } else {
                ftpClient.setSoTimeout(FTP_TIMEOUT);
                // login ftp server
                if (!ftpClient.login(FTP_USERNAME, FTP_PASSWORD)) {
                    throw new IOException("Username or password is incorrect!");
                }
                ftpClient.setDataTimeout(FTP_TIMEOUT);
                System.out.println("connected");
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * disconnect ftp server
     * 
     * @author viettuts.vn
     */
    private void disconnectFTPServer() {
        if (ftpClient != null && ftpClient.isConnected()) {
            try {
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Kết quả:

connecting ftp server...
connected
File /demo/autologin_v1.jar is downloading...
File /demo/autologin_v1.jar has been downloaded successfully.
File /demo/autologin_v2.jar is downloading...
File /demo/autologin_v2.jar has been downloaded successfully.
File /demo/autologin_v3.jar is downloading...
File /demo/autologin_v3.jar has been downloaded successfully.

Java là gì? Học java core
Lập trình hướng đối tượng(OOPs) trong java

Recent Updates

Bắt đầu với excelHướng dẫn lập trình Python với EclipseHướng dẫn lập trình Python với PyCharm Community EditionHướng dẫn lập trình Python với Visual Studio CodeLiên kết css với htmlSử dụng Javascript trong HTMLToán tử dấu 2 chấm (::) trong Java 8Lambda Expression - Biểu thức Lambda trong java 8Hướng dẫn lập trình Angular 7 với trình soạn thảo Visual Studio CodeBài tập Java - Sắp xếp nhanh (Quick Sort) trong JavaBài tập Java - Sắp xếp chèn (Insertion Sort) trong JavaBài tập Java - Sắp xếp nổi bọt (Bubble Sort) trong Java

VietTuts on facebook

Học Lập Trình Online Miễn Phí - VietTuts.Vn

Danh sách bài học

Học java
Học servlet
Học jsp
Học Hibernate
Học Struts2
Học Spring
Học SQL

Câu hỏi phỏng vấn

201 câu hỏi phỏng vấn java
25 câu hỏi phỏng vấn servlet
75 câu hỏi phỏng vấn jsp
52 câu hỏi phỏng vấn Hibernate
70 câu hỏi phỏng vấn Spring
57 câu hỏi phỏng vấn SQL

About VietTuts.Vn

Hệ thống bài học trên VietTuts.Vn bao gồm các bài lý thuyết và thực hành về các công nghệ java và công nghệ web. Các bài lý thuyết trên hệ thống VietTuts.Vn được tham khảo và tổng hợp từ các trang http://javatpoint.com, http://www.tutorialspoint.com, http://docs.oracle.com/en …

Scroll back to top

Copyright © 2016 VietTuts.Vn all rights reserved. | VietTuts.Vn team | Liên hệ | Chính sách - riêng tư | sitemap.html | sitemap_index.xml