Android 使用commons-net包进行FTP开发教程

来源:互联网 发布:书生电子图书数据库 编辑:程序博客网 时间:2024/06/05 23:06

Android 使用commons-net包进行FTP开发教程

这一篇博客将带大家分分钟搞定FTP需求(登录,上传,下载,列表,删除),站在巨人的肩膀上,我们都是代码的搬运工。


开发准备工作

创建一个新的Android工程先
然后先把我们会用到的框架引用进来,这里我是使用AS开发,所以大都直接在build.gradle配置文件中 (dependencies->compile) 了

build.gradle代码块

apply plugin: 'com.android.application'android {    compileSdkVersion 19    buildToolsVersion "24.0.0"    defaultConfig {        applicationId "com.ftp"        minSdkVersion 19        targetSdkVersion 23        versionCode 1        versionName "1.0"    }    buildTypes {        release {            minifyEnabled false            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'        }    }}dependencies {    compile 'com.android.support:recyclerview-v7:23.4.0'    compile 'io.reactivex:rxjava:1.1.1'    compile 'io.reactivex:rxandroid:1.1.0'    compile 'com.google.code.gson:gson:2.6.2'    compile 'com.squareup.retrofit2:retrofit:2.1.0'    compile 'com.squareup.retrofit2:converter-gson:2.1.0'    compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'    compile 'commons-net:commons-net:3.5'}

工程目录结构

1、开始FTP的基本流程登录

    /**     * 打开FTP服务.     *     * @throws IOException     */    public void openConnect() throws IOException {        // 中文转码        ftpClient.setControlEncoding("UTF-8");        int reply; // 服务器响应值        // 连接至服务器        ftpClient.connect(hostName);        // 获取响应值        reply = ftpClient.getReplyCode();        if (!FTPReply.isPositiveCompletion(reply)) {            // 断开连接            ftpClient.disconnect();            throw new IOException("connect fail: " + reply);        }        // 登录到服务器        ftpClient.login(userName, password);        // 获取响应值        reply = ftpClient.getReplyCode();        if (!FTPReply.isPositiveCompletion(reply)) {            // 断开连接            ftpClient.disconnect();            throw new IOException("connect fail: " + reply);        } else {            // 获取登录信息//            FTPClientConfig config = new FTPClientConfig(ftpClient.getSystemType().split(" ")[0]);//            config.setServerLanguageCode("zh");//            ftpClient.configure(config);            // 使用被动模式设为默认            ftpClient.enterLocalPassiveMode();            // 二进制文件支持            ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);            System.out.println("login");        }    }

这里需要用到的三个参数:
- hostName FTP服务器IP或域名
- userName 登录用户名
- password 登录密码
注意关于FTP操作的这些方法都不能在UI主线程中调用,不然会暴菊花,不对抛异常。所以项目中这些异步操作都是用Rxjava来处理的,刚学会用Rx,用的比较丑,勿怪。
回到正题,登录成功后我们得到 FTPClient ,这个就是下面一系列FTP操作的关键了。

2、获取FTP目录下文件列表

    /**     * 列出FTP下所有文件.     *     * @param remotePath 服务器目录     * @return FTPFile集合     * @throws IOException     */    public List<FTPFile> listFiles(String remotePath) throws IOException {        List<FTPFile> list=new ArrayList<>();        // 获取文件        FTPFile[] files = ftpClient.listFiles(remotePath);        // 遍历并且添加到集合        for (FTPFile file : files) {            list.add(file);        }        return list;    }

代码大简单了,不赘述。传入的是相对于FTP服务根目录的相对路径

    /**     * FTP根目录.     */    public static final String REMOTE_PATH = "/";

如果要开FTP根目录下文件传“/”就可以了
如果要获取子目录下文件列表自己改咯“/子目录/孙目录/”好了
当然还有一种方法可以获取,只是流程略有不同,本质都是一样的

    /**     * 列出FTP下所有文件.     *     * @param remotePath 服务器目录     * @return FTPFile集合     * @throws IOException     */    public List<FTPFile> listFiles2(String remotePath) throws IOException {        List<FTPFile> list=new ArrayList<>();        // 更改FTP当前目录        ftpClient.changeWorkingDirectory(remotePath);        // 得到FTP当前目录下所有文件        FTPFile[] ftpFiles = ftpClient.listFiles();        // 遍历并且添加到集合        for (FTPFile file : ftpFiles) {            list.add(file);        }        return list;    }

3、FTP下载文件

    /**     * 下载.     *     * @param remotePath FTP目录     * @param fileName   文件名     * @param localPath  本地目录     * @return Result     * @throws IOException     */    public Result download(String remotePath, String fileName, String localPath) throws IOException {        boolean flag = true;        Result result = null;        // 初始化FTP当前目录        currentPath = remotePath;        // 初始化当前流量        response = 0;        // 更改FTP目录        ftpClient.changeWorkingDirectory(remotePath);        // 得到FTP当前目录下所有文件        FTPFile[] ftpFiles = ftpClient.listFiles();        // 循环遍历        for (FTPFile ftpFile : ftpFiles) {            // 找到需要下载的文件            if (ftpFile.getName().equals(fileName)) {                System.out.println("download...");                // 创建本地目录                File file = new File(localPath + "/" + fileName);                // 下载前时间                Date startTime = new Date();                if (ftpFile.isDirectory()) {                    // 下载多个文件                    flag = downloadMany(file);                } else {                    // 下载当个文件                    flag = downloadSingle(file, ftpFile);                }                // 下载完时间                Date endTime = new Date();                // 返回值                result = new Result(flag, Util.getFormatTime(endTime.getTime() - startTime.getTime()), Util.getFormatSize(response));            }        }        return result;    }
    /**     * 下载单个文件.     *     * @param localFile 本地目录     * @param ftpFile   FTP目录     * @return true下载成功, false下载失败     * @throws IOException     */    private boolean downloadSingle(File localFile, FTPFile ftpFile) throws IOException {        Gson g=new Gson();        Log.d("FTP",g.toJson(localFile));        Log.d("FTP",g.toJson(ftpFile));        boolean flag = true;        // 创建输出流        OutputStream outputStream = new FileOutputStream(localFile);        // 统计流量        response += ftpFile.getSize();        // 下载单个文件        flag = ftpClient.retrieveFile(localFile.getName(), outputStream);        // 关闭文件流        outputStream.close();        return flag;    }

4、上传文件到FTP服务器

    /**     * 上传.     *     * @param localFile  本地文件     * @param remotePath FTP目录     * @return Result     * @throws IOException     */    public Result uploading(File localFile, String remotePath) throws IOException {        boolean flag = true;        Result result = null;        // 初始化FTP当前目录        currentPath = remotePath;        // 初始化当前流量        response = 0;        // 二进制文件支持        ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);        // 使用被动模式设为默认        ftpClient.enterLocalPassiveMode();        // 设置模式        ftpClient.setFileTransferMode(org.apache.commons.net.ftp.FTP.STREAM_TRANSFER_MODE);        // 改变FTP目录        ftpClient.changeWorkingDirectory(REMOTE_PATH);        // 获取上传前时间        Date startTime = new Date();        if (localFile.isDirectory()) {            // 上传多个文件            flag = uploadingMany(localFile);        } else {            // 上传单个文件            flag = uploadingSingle(localFile);        }        // 获取上传后时间        Date endTime = new Date();        // 返回值        result = new Result(flag, Util.getFormatTime(endTime.getTime() - startTime.getTime()), Util.getFormatSize(response));        return result;    }
    /**     * 上传单个文件.     *     * @param localFile 本地文件     * @return true上传成功, false上传失败     * @throws IOException     */    private boolean uploadingSingle(File localFile) throws IOException {        boolean flag = true;        // 创建输入流        InputStream inputStream = new FileInputStream(localFile);        // 统计流量        response += (double) inputStream.available() / 1;        // 上传单个文件        flag = ftpClient.storeFile(localFile.getName(), inputStream);        // 关闭文件流        inputStream.close();        return flag;    }

5、删除FTP上文件或文件夹

public Result removeFile(String remotePath,String srcFname) throws IOException {        boolean flag = false;        Result result = null;        ftpClient.changeWorkingDirectory(remotePath);        FTPFile[] ftpFiles = ftpClient.listFiles();        // 循环遍历        for (FTPFile ftpFile : ftpFiles) {            // 找到需要下载的文件            if (ftpFile.getName().equals(srcFname)) {                System.out.println("delete...");                // 创建本地目录                // 删除前时间                Date startTime = new Date();                if (ftpFile.isDirectory()) {                    // 删除多个文件                    flag = ftpClient.removeDirectory(srcFname);                } else {                    // 删除单个文件                    flag = ftpClient.deleteFile(srcFname);                }                // 删除完时间                Date endTime = new Date();                // 返回值                result = new Result(flag, Util.getFormatTime(endTime.getTime() - startTime.getTime()), Util.getFormatSize(response));            }        }        return result;    }

就像SQL一样,增删改查都有了,Apache的这个包好牛逼,有木有。

工程完整代码下载地址

0 0
原创粉丝点击