1. 程式人生 > >去伺服器的FTP路徑下上讀取檔案

去伺服器的FTP路徑下上讀取檔案

package com.sinosoft.util;

import java.io.BufferedReader;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.SocketException;

import org.apache.commons.net.ftp.FTPClient;

public class Ftp {

    /**

     * 去 伺服器的FTP路徑下上讀取檔案

     * 

     * @param ftpUserName

     * @param ftpPassword

     * @param ftpPath

     * @param FTPServer

     * @return

     */

    public static String readConfigFileForFTP(String ftpUserName, String ftpPassword,

                                              String ftpPath, String ftpHost, int ftpPort,

                                              String fileName) {

        StringBuffer resultBuffer = new StringBuffer();

        InputStream in = null;

        FTPClient ftpClient = null;

        System.out.println("開始讀取絕對路徑" + ftpPath + "檔案!");

        try {

            ftpClient = FTPUtil.getFTPClient(ftpHost, ftpPassword, ftpUserName, ftpPort);

            ftpClient.setControlEncoding("UTF-8"); // 中文支援

            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

            ftpClient.enterLocalPassiveMode();

            ftpClient.changeWorkingDirectory(ftpPath);

            in = ftpClient.retrieveFileStream(fileName);

        } catch (FileNotFoundException e) {

            System.out.println("沒有找到" + ftpPath + "檔案");

            e.printStackTrace();

            return "下載配置檔案失敗,請聯絡管理員.";

        } catch (SocketException e) {

            System.out.println("連線FTP失敗.");

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

            System.out.println("檔案讀取錯誤。");

            e.printStackTrace();

            return "配置檔案讀取失敗,請聯絡管理員.";

        }

        if (in != null) {

            BufferedReader br = new BufferedReader(new InputStreamReader(in));

            String data = null;

            try {

                while ((data = br.readLine()) != null) {

                    resultBuffer.append(data + "\n");

                }

            } catch (IOException e) {

                System.out.println("檔案讀取錯誤。");

                e.printStackTrace();

                return "配置檔案讀取失敗,請聯絡管理員.";

            } finally {

                try {

                    ftpClient.disconnect();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        } else {

            System.out.println("in為空,不能讀取。");

            return "配置檔案讀取失敗,請聯絡管理員.";

        }

        System.out.println("resultBuffer.toString()=" + resultBuffer.toString());

        return resultBuffer.toString();

    }

    public static void main(String[] args) {

        readConfigFileForFTP("dawei", "gjjl302", "Zdy", "218.60.42.207", 21, "upload/22.txt");

    }

}