1. 程式人生 > >FTPClient 遠端檔案讀寫(Java)

FTPClient 遠端檔案讀寫(Java)

apache.common.net.ftp
NOT sun.net.ftp

public class FtpTest{
    /**
    *向ftp寫檔案
    */
    public boolean uploadFile(
        String content, //要寫入的內容
        String username, //ftp登入使用者名稱
        String password, //ftp登入密碼
        String hostname, //主機名 ,ip
        String filename, //建立的檔名
        String path      //指定寫入目錄
        ){
        boolean
flag = false; FTPClient ftpClient = new FTPClient(); try{ InputStream is = null; int reply; //1.輸入流 is = new ByteArrayInputStream(content.getBytes()); //2.連線伺服器,採用預設埠21 ftpClient.connect(hostname); //3.登入ftp
ftpClient.login(username , password); reply = ftpClient.getReplyCode(); if(!FTPReply.isPositiveCompletion(reply)){ ftp.disconnect(); return flag; } //4.指定寫入的目錄 ftpClient.changeWorkingDirectory(path); //5.寫操作
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.storeFile(new String(filename.getBytes("utf-8"),"iso-8859-1"),is); is.close(); //退出 ftp.logout(); flag = true; }catche(Exception e) { e.printStackTrace(); }finally{ if(ftpClient.isConnected()){ try{ ftpClient.disconnect(); }catch(Exception e){ e.printStackTrace(); } } } return flag; } } /** *下載與上傳一致,只是一個是寫,一個是讀 */ ...... //指定要下載的目錄 ftpClient.changeWorkingDirectory(path); FTPFile[] fs = ftp.listFiles();//目錄下的檔案list for(FTPFile ff:fs){ byte[] bytes = ff.getName().getBytes("iso-8859-1"); String fn = new String(bytes , "utf-8"); if(fn.equals(fileName)){ //判斷是否是要下載的檔案fileName File localFile = new File(localPath + ff.getName());//localPath 本地儲存的目錄 OutputStream is = new FileOutputStream(localFile); ftpClient.retrieveFile(ff.getName() , is); is.close(); } }

根據需求,我嘗試了寫檔案的一些不同情況

 /*
    寫檔案apkInfoFileName:
    若檔案不存在,則新建檔案apkInfoFileName,寫入內容versionCode+path;
    若檔案存在,則向檔案中追加內容"\n"+versionCode+path;
 */
 OutputStreamWriter out = new OutputStreamWriter(ftp.appendFileStream(apkInfoFileName));
            BufferedWriter bw = new BufferedWriter(out);
            bw.write("\n"+versionCode+path);
            bw.flush();
            bw.close();
            out.close();

發現上傳不上去,有這幾點原因

防火牆

環境:Centos7
我在雜項裡找到防火牆,點選區域裡的public,勾上ftp

FTPClient.enterLocalPassiveMode()

FTPClient連線前呼叫FTPClient.enterLocalPassiveMode();這個方法的意思就是每次資料連線之前,ftp client告訴ftp server開通一個埠來傳輸資料。為什麼要這樣做呢,因為ftp server可能每次開啟不同的埠來傳輸資料,但是在linux上,由於安全限制,可能某些埠沒有開啟,所以就出現阻塞。

MORE

listDirectories();
listnames()