java ftp,java

來源:互聯網
上載者:User

java ftp,java

FTPUtil

 

import java.io.File;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 org.apache.commons.net.ftp.FTPClient;import org.apache.commons.net.ftp.FTPFile;import org.apache.commons.net.ftp.FTPReply;public class FTPUtil {    // public static final String platform_charset = "utf-8";    public static final String platform_charset = "gb2312";    public static boolean uploadFile(String url, int port, String username,            String password, String path, String filename, InputStream input)            throws IOException {        boolean success = false;        FTPClient ftp = new FTPClient();        try {            int reply;            ftp.connect(url, port);            ftp.login(username, password);            reply = ftp.getReplyCode();            if (!FTPReply.isPositiveCompletion(reply)) {                ftp.disconnect();                return success;            }            path = path.replaceAll("//", "/");            if (path.startsWith("/"))                path = path.substring(1);            if (filename.startsWith("/"))                filename = filename.substring(1);            String dir = new String(path.getBytes(platform_charset),"iso-8859-1");            String destName = new String(filename.getBytes(platform_charset),"iso-8859-1");            buildList(ftp, dir);            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);            ftp.changeWorkingDirectory(dir);            boolean flag = ftp.storeFile(destName, input);            input.close();            ftp.logout();            if (flag)                 success = true;        } finally {            if (ftp.isConnected()) {                try {                    ftp.disconnect();                } catch (IOException ioe) {                    ioe.printStackTrace();                }            }        }        return success;    }    public static void sendFile(String url, int port,            String username, String password, String path, String filename,            InputStream input) throws IOException {        FTPClient ftp = new FTPClient();        try {            int reply;            ftp.connect(url, port);            ftp.login(username, password);            reply = ftp.getReplyCode();            if (!FTPReply.isPositiveCompletion(reply)) {                ftp.disconnect();                return;            }            if (path.startsWith("/"))                path = path.substring(1);            if (filename.startsWith("/"))                filename = filename.substring(1);            String dir = new String(path.getBytes(platform_charset),                    "iso-8859-1");            String destName = new String(filename.getBytes(platform_charset),                    "iso-8859-1");            buildList(ftp, dir);            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);            ftp.changeWorkingDirectory(dir);            int n = -1;            long trans = 0;            int bufferSize = ftp.getBufferSize();            byte[] buffer = new byte[bufferSize];            OutputStream outputstream = ftp.storeFileStream(destName);            while ((n = input.read(buffer)) != -1) {                outputstream.write(buffer);                trans += n;            }            input.close();            ftp.logout();        } finally {            if (ftp.isConnected()) {                try {                    ftp.disconnect();                } catch (IOException ioe) {                    ioe.printStackTrace();                }            }        }    }    public static void buildList(FTPClient ftpclient, String pathList)            throws IOException {        StringTokenizer s = new StringTokenizer(pathList, "/");        String pathName = "";        while (s.hasMoreElements()) {            pathName = pathName + "/" + (String) s.nextElement();            if (pathName.startsWith("/"))                pathName = pathName.substring(1);            ftpclient.makeDirectory(pathName);        }    }    public static boolean downFile(String url, int port, String username,            String password, String remotePath, String fileName,            String localPath) throws IOException {        boolean success = false;        FTPClient ftp = new FTPClient();        try {            int reply;            ftp.connect(url, port);            ftp.login(username, password);            reply = ftp.getReplyCode();            if (!FTPReply.isPositiveCompletion(reply)) {                ftp.disconnect();                return success;            }            remotePath = new String(remotePath.getBytes(platform_charset),                    "iso-8859-1");            ftp.changeWorkingDirectory(remotePath);            FTPFile[] fs = ftp.listFiles();            for (FTPFile ff : fs) {                String name = ff.getName();                name = new String(name.getBytes("iso-8859-1"), platform_charset);                if (name.equals(fileName)) {                    File localPathFile = new File(localPath);                    //判斷路徑是否存在 ,不存在則建立                    if(!localPathFile.exists()){                        localPathFile.mkdirs();                    }                    File localFile = new File(localPath + "/" + name);                                        OutputStream os = new FileOutputStream(localFile);                    ftp.retrieveFile(ff.getName(), os);                    os.close();                }            }            ftp.logout();            success = true;        } finally {            if (ftp.isConnected()) {                try {                    ftp.disconnect();                } catch (IOException ioe) {                }            }        }        return success;    }    public static List<FTPFile> list(String url, int port, String username,            String password, String remotePath) throws Exception {        FTPClient ftp = new FTPClient();        List<FTPFile> list = new ArrayList<FTPFile>();        try {            int reply;            ftp.connect(url, port);            ftp.login(username, password);            reply = ftp.getReplyCode();            if (!FTPReply.isPositiveCompletion(reply)) {                ftp.disconnect();                return list;            }            remotePath = new String(remotePath.getBytes(platform_charset),                    "iso-8859-1");            ftp.changeWorkingDirectory(remotePath);            FTPFile[] files = ftp.listFiles();            for (FTPFile f : files) {                String name = f.getName();                if (name.equals(".") || name.equals("..")                        || name.equals("Thumbs.db"))                    continue;                list.add(f);            }            return list;        } catch (IOException e) {            e.printStackTrace();            return list;        } finally {            ftp.logout();            if (ftp.isConnected()) {                try {                    ftp.disconnect();                } catch (IOException ioe) {                }            }        }    }    public static boolean hasSubFolder(FTPClient ftp, String parent)            throws IOException {        FTPFile[] files = ftp.listFiles(parent);        for (FTPFile f : files) {            String name = f.getName();            if (name.equals(".") || name.equals("..")                    || name.equals("Thumbs.db"))                continue;            if (f.isDirectory()) {                return true;            } else {                continue;            }        }        return false;    }    public static boolean deleteFile(String url, int port, String username,            String password, String remotePath) throws IOException {        boolean success = false;        FTPClient ftp = new FTPClient();        try {            int reply;            ftp.connect(url, port);            ftp.login(username, password);            reply = ftp.getReplyCode();            if (!FTPReply.isPositiveCompletion(reply)) {                ftp.disconnect();                return success;            }            remotePath = new String(remotePath.getBytes(platform_charset),                    "iso-8859-1");            if (remotePath.startsWith("/"))                remotePath = remotePath.substring(1);            ftp.changeWorkingDirectory(remotePath);            FTPFile[] fs = ftp.listFiles();            for (FTPFile ff : fs) {                String name = ff.getName();                ftp.deleteFile(name);            }            ftp.changeToParentDirectory();            int p = remotePath.lastIndexOf("/");            String folderName = remotePath.substring(p + 1);            ftp.removeDirectory(folderName);            ftp.logout();            success = true;        } finally {            if (ftp.isConnected()) {                try {                    ftp.disconnect();                } catch (IOException ioe) {                }            }        }        return success;    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.