Hàm Java FTP Tải xuống, tải lên, lấy danh sách tập tin, kết nối, ngắt kết nối sử dụng Apache Common NET. | Java FTP Function Download, Upload, Get List File, Connect, Disconnect Using Apache Common NET.

Đây là một lớp Java FTP function do mình tạo trong lúc làm dự án, có các chức năng Download, Upload, GetListFile, Connection Disconnect  trên FTP, mình lưu lại để tái sử dụng sau này, bạn nào thấy hữu ích phần nào thì cứ copy về xài nha ^^!. À quên mình sử dụng mã nguồn mở của Apache Commons NET, bạn cần download thư việc này về add vào project trước khi sử dụng.

Java FTP Function
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package citi_support_tools;

/**
 *
 * @author bnson
 */
import java.awt.EventQueue;
import java.io.ByteArrayOutputStream;
import 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.PrintStream;
import java.io.PrintWriter;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import org.apache.commons.io.output.CountingOutputStream;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.io.CopyStreamAdapter;
import static org.junit.Assert.*;

public class FTPFunctions {

    // Creating FTP Client instance   
    FTPClient ftp = null;
    public boolean logStatus;
   
   
    // Constructor to connect to the FTP Server
    public FTPFunctions(String host, int port, String username, String password) throws Exception {

        PrintStream printStreamOriginal=System.out;
        System.setOut(new PrintStream(new OutputStream(){
            @Override
            public void write(int b) {
            }
        }));       
       
        ftp = new FTPClient();
        ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
        int reply;
        ftp.connect(host, port);
        System.out.println("FTP URL is:" + ftp.getDefaultPort());
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            throw new Exception("Exception in connecting to FTP Server");
        }
        System.out.println("---------------------------------------");

        System.out.println("this text will be lost");

        logStatus = ftp.login(username, password);
       
       
        System.out.println("---------------------------------------");
        ftp.enterLocalPassiveMode();
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
       
        System.out.println("---------------------------------------");
       
        System.setOut(printStreamOriginal);
       
        System.out.println("Login status: " + logStatus);
    }

    // Method to upload the File on the FTP Server
    public void uploadFTPFile(String localFileFullName, String fileName, String hostDir) throws Exception {
        try {
            int size;
            InputStream input = new FileInputStream(new File(localFileFullName));
           
            //ftp.enterLocalPassiveMode();
            //ftp.setFileType(FTP.BINARY_FILE_TYPE);
           
            System.out.println("Status upload: " + this.ftp.storeFile(hostDir + fileName, input));
            input.close();
            ftp.disconnect();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
   
    public void uploadFTPFile02(String localFileFullName, String fileName, String hostDir,final int r,final int c) throws Exception {
        try {
            int size;
            InputStream input = new FileInputStream(new File(localFileFullName));
           
            //ftp.enterLocalPassiveMode();
            //ftp.setFileType(FTP.BINARY_FILE_TYPE);
            if (this.ftp.storeFile(hostDir + fileName, input)) {
                Citi_Support_Tools.jTable1.getModel().setValueAt("Upload Success", r, c);
            } else {
                Citi_Support_Tools.jTable1.getModel().setValueAt("Upload Fail", r, c);
            }
           
           
            input.close();
            ftp.disconnect();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }   
   
    public double getUpload = 0;
    public double getSize = 0;
    public void uploadFTPFile01(String localFileFullName, String fileName, String hostDir,final int r,final int c) {
        try {
           
            this.ftp.enterLocalPassiveMode();
            this.ftp.enterLocalActiveMode();
            System.out.println("Local Name: " + localFileFullName);
           
            File tmp = new File(localFileFullName);
            InputStream inputStream = new FileInputStream(new File(localFileFullName));
            //InputStream inputStream = new FileInputStream(localFileFullName);
            OutputStream outputStream = this.ftp.storeFileStream(hostDir + fileName);
            //this.ftp.makeDirectory(hostDir + "TEST");
            System.out.println(hostDir + fileName);
           
            byte[] bytesIn = new byte[1024];
            int read = 0;
           
            getSize = tmp.length();
            System.out.println("File Size: " + getSize);
           
            while ((read = inputStream.read(bytesIn)) != -1) {
                outputStream.write(bytesIn, 0, read);
                getUpload += read;
               
//                final double tread = getUpload;
//                Citi_Support_Tools.jTable1.getModel().setValueAt(tread, r, c);

//                Citi_Support_Tools.model.setValueAt(read, r, c);
//                Citi_Support_Tools.model.fireTableCellUpdated(r, c);
//                Citi_Support_Tools.model.fireTableDataChanged();
//                Citi_Support_Tools.jTable1.validate();
//                Citi_Support_Tools.jTable1.repaint();
                       
                System.out.println("Download: " + getUpload);
               
            }
           
            //System.out.println("Upload Size: " + getUpload);
            //outputStream.flush();
            inputStream.close();
            //outputStream.close();

            ftp.disconnect();
           
        } catch (Exception e) {
            e.printStackTrace();
        }
    } 

    // Download the FTP File from the FTP Server
    public void downloadFTPFile(String source, String destination) {
        try {
            FileOutputStream fos = new FileOutputStream(destination);
            this.ftp.retrieveFile(source, fos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // list the files in a specified directory on the FTP
    public boolean listFTPFiles(String directory, String fileName) throws IOException {
        // lists files and directories in the current working directory
        boolean verificationFilename = false;
        FTPFile[] files = ftp.listFiles(directory);
        for (FTPFile file : files) {
            String details = file.getName();
            System.out.println(details);
            if (details.equals(fileName)) {
                System.out.println("Correct Filename");
                verificationFilename = details.equals(fileName);
                assertTrue("Verification Failed: The filename is not updated at the CDN end.", details.equals(fileName));
            }
        }

        return verificationFilename;
    }

    // Disconnect the connection to FTP
    public void disconnect() {
        if (this.ftp.isConnected()) {
            try {
                this.ftp.logout();
                this.ftp.disconnect();
            } catch (IOException f) {
                // do nothing as file is already saved to server
            }
        }
    }
}



No comments:

Post a Comment