FTP搭建

什么是FTP

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

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


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


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


    image.png
  • 在“網(wǎng)站”文件夾右鍵添加ftp站點


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


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


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


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

打開瀏覽器,輸入網(wǎng)址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文本內(nèi)容的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??????
         */
    }
    
    
    /*????????*/
}
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容