遠程FTP處理Java類

jopen 12年前發布 | 36K 次閱讀 Java FTP 文件上傳

項目需要和其他系統實現數據同步(非及時接口),也就是要把該系統產生的數據上傳到FTP服務器上,供其他系統下載實現同步。代碼如下 :

package com.zte.pp.usermsgsync;

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

/**

/**
 * 遠程FTP上傳文件
 * @param remotePath
 * @param localPath
 * @param files
 * <a  class="referer" target="_blank">@return</a> 
 * @throws Exception
 */
public File uploadFile(String remotePath, List<File> files)throws Exception {
    File fileIn = null;
    OutputStream os = null;
    FileInputStream is = null;
    try 
    {
        for (File file : files) 
        {
            if (connectServer(this.getIp(), this.getPort(), this.getUser(),this.getPwd())) 
            {
                System.out.println("----進入文件上傳到FTP服務器--->");
                ftpClient.changeWorkingDirectory(remotePath);
                os = ftpClient.storeFileStream(file.getName());
                fileIn = file;
                is = new FileInputStream(fileIn);
                byte[] bytes = new byte[1024];
                int c;
                while ((c = is.read(bytes)) != -1)
                {
                    os.write(bytes, 0, c);
                }
            }
        }
    } 
    catch (Exception e) 
    {
        logger.error("上傳FTP文件異常: ", e);
    } 
    finally
    {
        os.close();
        is.close();
        ftpClient.logout();
        if (ftpClient.isConnected())
        {
            ftpClient.disconnect();
        }
    }

    return fileIn;
}


/**

} catch (Exception ex) {
   logger.error("遠程刪除FTP文件異常: ", ex);
   ex.printStackTrace(); 
} return flag; }
/**
 * 遠程FTP刪除目錄下的所有文件
 * @param remotePath
 * @param localPath
 * <a  class="referer" target="_blank">@return</a> 
 * @throws Exception
 */
public void deleteAllFile(String remotePath, String localPath) throws Exception 
{
    try 
    {
        if (connectServer(this.getIp(), this.getPort(), this.getUser(),this.getPwd())) 
        {
            ftpClient.changeWorkingDirectory(remotePath);
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for (FTPFile file : ftpFiles) 
            {
                ftpClient.deleteFile(file.getName());

            }
        }
    } 
    catch (Exception e) 
    {
        logger.error("從FTP服務器刪除文件異常:", e);
        e.printStackTrace();
    } 
    finally 
    {
        ftpClient.logout();
        if (ftpClient.isConnected())
        {
            ftpClient.disconnect();
        }
    }
}


/**

/**
 * 遠程FTP下載文件
 * 
 * @param remotePath
 * @param localPath
 * <a  class="referer" target="_blank">@return</a> 
 * @throws Exception
 */
public List<File> downloadFile(String remotePath, String localPath ) throws Exception 
{
    List<File> result = new ArrayList<File>();
    File fileOut = null;
    InputStream is = null;
    FileOutputStream os = null;
    try 
    {
        if (connectServer(this.getIp(), this.getPort(), this.getUser(),this.getPwd())) 
        {
            ftpClient.changeWorkingDirectory(remotePath);
            FTPFile[] ftpFiles = ftpClient.listFiles();

            for (FTPFile file : ftpFiles) 
            {
                is = ftpClient.retrieveFileStream(file.getName());
                if (localPath != null && !localPath.endsWith(File.separator)) 
                {
                    localPath = localPath + File.separator;
                    File path = new File(localPath);
                    if (!path.exists()) 
                    {
                        path.mkdirs();
                    }
                }
                fileOut = new File(localPath + file.getName());
                os = new FileOutputStream(fileOut);
                byte[] bytes = new byte[1024];
                int c;
                while ((c = is.read(bytes)) != -1) 
                {
                    os.write(bytes, 0, c);
                }

                result.add(fileOut);
                ftpClient.completePendingCommand();
                os.flush();
                is.close();
                os.close();
            }

            for (FTPFile file : ftpFiles) 
            {
                ftpClient.deleteFile(file.getName());
            }
        }
    } 
    catch (Exception e) 
    {
        logger.error("從FTP服務器下載文件異常:", e);
        e.printStackTrace();
    } 
    finally 
    {
        ftpClient.logout();
        if (ftpClient.isConnected())
        {
            ftpClient.disconnect();
        }
    }

    return result;
}




public String getIp() {
    return ip;
}

public void setIp(String ip) {
    this.ip = ip;
}

public int getPort() {
    return port;
}

public void setPort(int port) {
    this.port = port;
}

public String getPwd() {
    return pwd;
}

public void setPwd(String pwd) {
    this.pwd = pwd;
}

public String getUser() {
    return user;
}

public void setUser(String user) {
    this.user = user;
}


/**
 * 測試方法
 * @param args
 */
public static void main(String[] args)
{
    String ip = "10.123.148.88";
    int port = 21 ; 
    String user ="root";   
    String pwd ="root"  ;   
    String remotePath = "http://home//V010//01//000011//" ;

    //上傳文件配置

// List<File> fileList = new ArrayList<File>(); //// File onefile = new File("F:\V010\01\000011\RSP\0100001120120701122712_Day.txt"); // File onefile = new File("F:\V010\01\000011\RSP\" ,"01000011201209263112839_Day.txt"); // System.out.println("----本地文件路徑--->"+ onefile.getAbsolutePath()); // fileList.add(onefile);

    FTPUtil ftpupload = new FTPUtil(ip,port,user,pwd);
    try 
    {

// ftpupload.uploadFile(remotePath, fileList); //測試上傳文件

        //刪除文件

// String remotefilename = remotePath+"01000011201209263112839_Day.txt"; // System.out.println("----遠程FTF上的文件名----"+remotefilename); // ftpupload.deleteFile(remotefilename);

        //下載目錄下所有的文件
        String localPath = "F:\\TEST\\" ;

// ftpupload.downloadFile(remotePath, localPath);

        ftpupload.deleteAllFile(remotePath, localPath);

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

}</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!