FTP搭建

什么是FTP

ftp是文件傳輸協(xié)議瑞驱,用于在網絡上傳輸文件的協(xié)議,可以簡單理解為ftp是一個服務器浸间,我們可以把文件上傳到ftp服務上恨憎,也可以從ftp上下載文件

在本機上搭建一個ftp服務(這里以win7系統(tǒng)為例)
  • 首先win+R,輸入optionalfeatures


    image.png
  • 找到Internet信息服務验夯,將FTP服務器和web管理工具選中猖吴,其子目錄也要選中


    image.png
  • 然后點擊確定,會看到IIS服務正在安裝挥转,讓你等幾分鐘
    安裝完之后海蔽,右鍵我的電腦,管理绑谣,左側菜單最下邊党窜,服務和應用程序,展開借宵,Internet信息服務


    image.png
  • 在“網站”文件夾右鍵添加ftp站點


    image.png
  • 添加站點名稱和物理路徑幌衣,物理路徑自己隨便新建個文件夾就行,下一步


    image.png
  • Ip地址選擇自己電腦的ip壤玫,SSL選擇允許豁护,ftp服務的默認端口為21,下一步


    image.png
  • 身份驗證選 “基本”欲间,訪問權限“所有用戶”楚里,可讀可寫


    image.png
  • 點擊完成,你會在網站的文件夾下看到你剛剛新建的站點
驗證一下我們搭建的ftp服務

打開瀏覽器猎贴,輸入網址ftp://192.168.119.80班缎,這個ip是你本機的ip

image.png

你可以在剛剛的物理路徑下放一個文件蝴光,搭建成功

ftp搭建好之后,我們來用Java代碼連接到ftp并上傳一個文件

直接上代碼:

FtpUtil ftpclient= new FtpUtil(ip,port,username,password);
                    try {
                        ftpclient.connectServer();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        throw new AppException("登錄FTP出錯!");
                    }
                    try {
                        ftpclient.uploadFileByContent(fileName, data);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        throw new AppException("上傳文件失敗!");
                    }

注意:這里上傳的是具有txt文本內容的String類型的字符串data吝梅,而不是文本類型file虱疏,F(xiàn)tpUtil這個類中有各種方法,一看就能懂

附上FtpUtil.java代碼

package com.neusoft.si.simis.local.treatment.payment;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;

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.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;

public class FtpUtil {
    private String ip = "";
    private String username = "";
    private String password = "";
    private int port = -1;
    private String path = "";
    FtpClient ftpClient = null;
    OutputStream os = null;
    FileInputStream is = null;

    public FtpUtil(String serverIP, String username, String password) {
        this.ip = serverIP;
        this.username = username;
        this.password = password;
    }

    
    
    public FtpUtil(String serverIP, int port, String username, String password) {
        this.ip = serverIP;
        this.username = username;
        this.password = password;
        this.port = port;
    }

    /**
     * ????ftp??????
     * 
     * @throws IOException
     */
    public boolean connectServer() {
        ftpClient = new FtpClient();
        try {
            if (this.port != -1) {
                ftpClient.openServer(this.ip, this.port);
            } else {
                ftpClient.openServer(this.ip);
            }
            ftpClient.login(this.username, this.password);
            if (this.path.length() != 0) {
                ftpClient.cd(this.path);// path??ftp????????????????
            }
            ftpClient.binary();// ??2?????????????
            System.out.println("??????\"" + ftpClient.pwd() + "\"??");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * ?????ftp??????????
     * 
     * @throws IOException
     */
    public boolean closeServer() {
        try {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
            if (ftpClient != null) {
                ftpClient.closeServer();
            }
            System.out.println("???????????");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * ??????????????????????
     * 
     * @param dir
     * @return
     */
    private boolean isDirExist(String dir) {
        String pwd = "";
        try {
            pwd = ftpClient.pwd();
            ftpClient.cd(dir);
            ftpClient.cd(pwd);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * ???????′????????
     * 
     * @param dir
     * @return
     * @throws Exception
     */
    private boolean createDir(String dir) {
        try {
            ftpClient.ascii();
            StringTokenizer s = new StringTokenizer(dir, "/"); // sign
            s.countTokens();
            String pathName = ftpClient.pwd();
            while (s.hasMoreElements()) {
                pathName = pathName + "/" + (String) s.nextElement();
                try {
                    ftpClient.sendServer("MKD " + pathName + "\r\n");
                } catch (Exception e) {
                    e = null;
                    return false;
                }
                ftpClient.readServerResponse();
            }
            ftpClient.binary();
            return true;
        } catch (IOException e1) {
            e1.printStackTrace();
            return false;
        }
    }

    /**
     * ftp??? ??????????????????filename??????У?????????????????????????????????????滻
     * 
     * @param filename
     *            ?????????????????У???
     * @return
     * @throws Exception
     */
    public boolean upload(String filename) {
        String newname = "";
        if (filename.indexOf("/") > -1) {
            newname = filename.substring(filename.lastIndexOf("/") + 1);
        } else {
            newname = filename;
        }
        return upload(filename, newname);
    }

    /**
     * ftp??? ??????????????????newName??????У?????????????????????????????????????滻
     * 
     * @param fileName
     *            ?????????????????У???
     * @param newName
     *            ????????????????????????У???
     * @return
     */
    public boolean upload(String fileName, String newName) {
        try {
            String savefilename = new String(fileName.getBytes("GBK"), "GBK");
            File file_in = new File(savefilename);// ???????????
            if (!file_in.exists()) {
                throw new Exception("????????????[" + file_in.getName() + "]?????????!");
            }
            if (file_in.isDirectory()) {
                upload(file_in.getPath(), newName, ftpClient.pwd());
            } else {
                uploadFile(file_in.getPath(), newName);
            }
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Exception e in Ftp upload(): " + e.toString());
            return false;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * ????????????????
     * 
     * @param fileName
     * @param newName
     * @param path
     * @throws Exception
     */
    private void upload(String fileName, String newName, String path)
            throws Exception {
        String savefilename = new String(fileName.getBytes("ISO-8859-1"), "GBK");
        File file_in = new File(savefilename);// ???????????
        if (!file_in.exists()) {
            throw new Exception("????????????[" + file_in.getName() + "]?????????!");
        }
        if (file_in.isDirectory()) {
            if (!isDirExist(newName)) {
                createDir(newName);
            }
            ftpClient.cd(newName);
            File sourceFile[] = file_in.listFiles();
            for (int i = 0; i < sourceFile.length; i++) {
                if (!sourceFile[i].exists()) {
                    continue;
                }
                if (sourceFile[i].isDirectory()) {
                    this.upload(sourceFile[i].getPath(), sourceFile[i]
                            .getName(), path + "/" + newName);
                } else {
                    this.uploadFile(sourceFile[i].getPath(), sourceFile[i]
                            .getName());
                }
            }
        } else {
            uploadFile(file_in.getPath(), newName);
        }
        ftpClient.cd(path);
    }

    /**
     * upload ??????
     * 
     * @param filename
     *            ???????????
     * @param newname
     *            ?????????????
     * @return -1 ????????? >=0 ??????????????????С
     * @throws Exception
     */
    public long uploadFile(String filename, String newname) throws Exception {
        long result = 0;
        TelnetOutputStream os = null;
        FileInputStream is = null;
        try {
            java.io.File file_in = new java.io.File(filename);
            if (!file_in.exists())
                return -1;
            os = ftpClient.put(newname);
            result = file_in.length();
            is = new FileInputStream(file_in);
            byte[] bytes = new byte[1024];
            int c;
            while ((c = is.read(bytes)) != -1) {
                os.write(bytes, 0, c);
            }
        } finally {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
        }
        return result;
    }
    /**
     * upload ??????
     * 
     * @param filename
     *            ???????????
     * @param newname
     *            ?????????????
     * @return -1 ????????? >=0 ??????????????????С
     * @throws Exception
     */
    public long uploadFileByContent(String filename, String Content) throws Exception {
        long result = 0;
        TelnetOutputStream os = null;
        try {
            os = ftpClient.put(filename);
            result = Content.length();
            
            byte[] bytes = Content.getBytes();
            int c=bytes.length;
            os.write(bytes, 0,c );
        } finally {
            if (os != null) {
                os.close();
            }
        }
        return result;
    }
    

    /**
     * ??ftp?????????????
     * 
     * @param filename
     *            ??????????????
     * @param newfilename
     *            ?????????????
     * @return
     * @throws Exception
     */
    public InputStream downloadFile(String filename) {
        long result = 0;
        TelnetInputStream is = null;
        FileOutputStream os = null;
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); 
        InputStream downloadis = null;

        try {
            is = ftpClient.get(filename);
            
            //java.io.File outfile = new java.io.File(newfilename);
            //os = new FileOutputStream(outfile);
            byte[] bytes = new byte[1024];
            int c;
            while ((c = is.read(bytes)) != -1) {
                swapStream.write(bytes, 0, c);
                //result = result + c;
            }
            byte[] swapByteArray = swapStream.toByteArray(); 
            downloadis= new ByteArrayInputStream(swapByteArray); 
         
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return downloadis;
    }

    /**
     * ?????????????????????????????????б?
     * 
     * @param path
     * @return
     */
    public List getFileList(String path) {
        List list = new ArrayList();
        DataInputStream dis;
        try {
            dis = new DataInputStream(ftpClient.nameList(this.path + path));
            String filename = "";
            while ((filename = dis.readLine()) != null) {
                list.add(filename);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
    /**
     * 
     * <p>???ftp??????</p>
     * @author newname 2012-12-26
     * @param srcFname
     * @return true || false
     */
    public boolean removeFile(String filename) throws Exception {
    boolean flag = false;
    if( ftpClient!=null ){
    try {
    // ftpClient.cd(url);
    ftpClient.sendServer("DELE "+filename+"\r\n");
    int status=ftpClient.readServerResponse();
    if(status==250 || status==226){
    flag=true;
    }
    }  catch (Exception e) {
    e.printStackTrace();
    System.err.println("Exception e in Ftp upload(): " + e.toString());
    return flag;
    } finally {
    try {
    if (is != null) {
    is.close();
    }
    if (os != null) {
    os.close();
    }
    } catch (IOException e) {
    e.printStackTrace();
    return flag;
    }
    }
    }
    return flag;
    }

    public static void main(String[] args) {
        FtpUtil ftp = new FtpUtil("192.168.11.11", "111", "1111");
        ftp.connectServer();
        boolean result = ftp.upload(
                "C:/Documents and Settings/ipanel/????/java/Hibernate_HQL.docx",
                "amuse/audioTest/music/Hibernate_HQL.docx");
        System.out.println(result ? "????????" : "???????");
        ftp.closeServer();
        /**
         * FTP????????б? USER PORT RETR ALLO DELE SITE XMKD CDUP FEAT PASS PASV STOR
         * REST CWD STAT RMD XCUP OPTS ACCT TYPE APPE RNFR XCWD HELP XRMD STOU
         * AUTH REIN STRU SMNT RNTO LIST NOOP PWD SIZE PBSZ QUIT MODE SYST ABOR
         * NLST MKD XPWD MDTM PROT
         * ????????????????,?????sendServer????????????(??????б???FTP????)?????????FTP?????????\r\n
         * ftpclient.sendServer("XMKD /test/bb\r\n"); //??з????????FTP????
         * ftpclient.readServerResponse??????sendServer?????
         * nameList("/test")???????μ?????б? XMKD????????????????????????δ?????????? XRMD?????
         * DELE??????
         */
    }
    
    
    /*????????*/
}
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末苏携,一起剝皮案震驚了整個濱河市做瞪,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌右冻,老刑警劉巖装蓬,帶你破解...
    沈念sama閱讀 218,525評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異纱扭,居然都是意外死亡牍帚,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評論 3 395
  • 文/潘曉璐 我一進店門乳蛾,熙熙樓的掌柜王于貴愁眉苦臉地迎上來暗赶,“玉大人,你說我怎么就攤上這事肃叶□逅妫” “怎么了?”我有些...
    開封第一講書人閱讀 164,862評論 0 354
  • 文/不壞的土叔 我叫張陵因惭,是天一觀的道長岳锁。 經常有香客問我,道長蹦魔,這世上最難降的妖魔是什么激率? 我笑而不...
    開封第一講書人閱讀 58,728評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮勿决,結果婚禮上乒躺,老公的妹妹穿的比我還像新娘。我一直安慰自己低缩,他們只是感情好聪蘸,可當我...
    茶點故事閱讀 67,743評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著表制,像睡著了一般。 火紅的嫁衣襯著肌膚如雪控乾。 梳的紋絲不亂的頭發(fā)上么介,一...
    開封第一講書人閱讀 51,590評論 1 305
  • 那天,我揣著相機與錄音蜕衡,去河邊找鬼壤短。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的久脯。 我是一名探鬼主播纳胧,決...
    沈念sama閱讀 40,330評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼帘撰!你這毒婦竟也來了跑慕?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,244評論 0 276
  • 序言:老撾萬榮一對情侶失蹤摧找,失蹤者是張志新(化名)和其女友劉穎核行,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體蹬耘,經...
    沈念sama閱讀 45,693評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡芝雪,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,885評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了综苔。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片惩系。...
    茶點故事閱讀 40,001評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖如筛,靈堂內的尸體忽然破棺而出堡牡,到底是詐尸還是另有隱情,我是刑警寧澤妙黍,帶...
    沈念sama閱讀 35,723評論 5 346
  • 正文 年R本政府宣布悴侵,位于F島的核電站,受9級特大地震影響拭嫁,放射性物質發(fā)生泄漏可免。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,343評論 3 330
  • 文/蒙蒙 一做粤、第九天 我趴在偏房一處隱蔽的房頂上張望浇借。 院中可真熱鬧,春花似錦怕品、人聲如沸妇垢。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽闯估。三九已至,卻和暖如春吼和,著一層夾襖步出監(jiān)牢的瞬間涨薪,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評論 1 270
  • 我被黑心中介騙來泰國打工炫乓, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留刚夺,地道東北人献丑。 一個月前我還...
    沈念sama閱讀 48,191評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像侠姑,于是被迫代替她去往敵國和親创橄。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,955評論 2 355

推薦閱讀更多精彩內容