关于FTP远程和服务器通信建立连接、增加、删除、下载、预览图片功能

来源:互联网 发布:get是什么意思网络上的 编辑:程序博客网 时间:2024/05/16 14:11

最近项目完工,闲暇之余抽出来时间给大家分享项目中用到的关于FTP和服务端交互的列子。本项目是基于串口编程,通过给串口发送指令给电子锁(文章后边简称e-lock)发送指令从而启动e-lock的wifi模块,然后手持机去连接wifi展开通信。
[这里是代码目录结构]
DelThread.java
FTPConstant.java
FTPHelper.java
RS232Activity.java
1. FTP远程建立连接

public static final String userName = "root";public static final String password = "root";public static final String url = "192.168.1.251";public static final int port = 21;public static final String fileName = AppUtil.createName(System.currentTimeMillis());public static final String localPath  = FileUtil.getNuctechPath();// 本地路径;public static final String remotePath = "/mnt/660010F011"; //FTP远程文件夹目录public static final int DELETE_ITEM = 001; //FTP通信`FTPClient ftp = FTPHelper.getConnectionFTP(FTPConstant.url,                        FTPConstant.port, FTPConstant.userName,                        FTPConstant.password);                        ftp.changeWorkingDirectory(FTPConstant.remotePath);// 转移到FTP服务器目录

2. 那么上一部建立连接拿到FtpClient的实例化对象之后 我们就要获取远程文件列表和本地缓存的文件列表

这里我们把文件加到list集合中便于比较

// 先从本地去取文件
picPath = FileUtil.getNuctechPath();// 本地路径
List fileDirList = FileUtil.getFileDirList(picPath);`
List ftpList = new ArrayList();
FTPFile[] listFiles = ftp.listFiles();
for (FTPFile ftpFile : listFiles) {
ImageItem item = new ImageItem();
item.setFileName(ftpFile.getName());
item.setImagePath(picPath);
ftpList.add(item);
}
3. 对比本地和远程的文件数量,也就是比大小,进而选择是去删除还是增加,要选取参照物。

if (ftpList.size() > fileDirList.size()) {    downDifFromFtp(ftpList, fileDirList);    mHandler.postDelayed(new Runnable() {        @Override        public void run() {           ActionToshowPicPage(FileUtil          .getFileDirList(picPath));        }    }, 300);} else if (ftpList.size() < fileDirList.size()) {        delectLocalDiffFtp(fileDirList, ftpList);        mHandler.postDelayed(new Runnable() {        @Override        public void run() {           ActionToshowPicPage(FileUtil          .getFileDirList(picPath));        }        }, 300);} else {      ActionToshowPicPage(fileDirList);}} catch (IOException e) {    e.printStackTrace();}好那么从以上代码片段大概意思也就能明白什么意思了如果远程文件个数大于本地缓存的,我们就要从远程下载本地所没有的;如果远程文件夹个数小于本地缓存的, 我们就要从本地进行删除多余的;反之我们就直接显示ftp文件列表这一部分我相信只要入门安卓工作一年应该就能看明白的那么下边附上代码核心部分 1. 下载 /** 2. 通过比对ftp远程文件和本地不同,进行下载 3.  4. @param ftpList 5. @param fileDirList 6.   */  private void downDifFromFtp(final List<ImageItem> ftpList,     final List<ImageItem> fileDirList) { List<String> uncontainList = FTPHelper.getUncontain((ArrayList<ImageItem>) ftpList, fileDirList);    for (String imageItem : uncontainList) {        if (AppUtil.isNetworkAvaiable(mContext)) {        picPath = FileUtil.getNuctechPath();// 本地路径        ftpDownload(FTPConstant.url, FTPConstant.port,        FTPConstant.userName, FTPConstant.password,        FTPConstant.remotePath,picPath, imageItem);        try {            Thread.sleep(300);        } catch (InterruptedException e) {                        e.printStackTrace();        }        } else {            showMsg(getString(R.string.net_error));        }    } 7. 删除   /**    * 通过比对local和ftp,如果本地有多余的立马删除    *     * @param fileDirList    * @param ftpList    */    private void delectLocalDiffFtp(List<ImageItem> ftpList, List<ImageItem> fileDirList) {  List<String> uncontainList = FTPHelper.getUncontain2(  (ArrayList<ImageItem>) ftpList, fileDirList);  for (String imageItem : uncontainList) {      DataCleanManager.deleteFile(picPath, imageItem);  } // 最后通知图库更新 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + picPath))); }} 8. 好了 最后一个跳转页面    /**     * 跳转到列表页面     *      * @param fileDirList     */ protected void ActionToshowPicPage(List<ImageItem>fileDirList) {    Intent intent = new Intent(mContext, ShowPicActivity.class);    intent.putExtra("fileList", (Serializable) fileDirList);    startActivity(intent);    closeLoadingDialog();}大体思路就到这里完成了。

9.写了这么多大家可能觉得代码有些乱不好理解,那么废话不多,果断上传核心的源码吧

public class FTPHelper {    /**     * 获得连接-FTP方式     *      * @param hostname     *            FTP服务器地址     * @param port     *            FTP服务器端口     * @param username     *            FTP登录用户名     * @param password     *            FTP登录密码     * @return FTPClient     */    public static FTPClient getConnectionFTP(String hostName, int port,            String userName, String passWord) {        // 创建FTPClient对象        FTPClient ftp = new FTPClient();        try {            // 连接FTP服务器            ftp.connect(hostName, port);            // 下面三行代码必须要,而且不能改变编码格式,否则不能正确下载中文文件            ftp.setControlEncoding("GBK");            FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);            conf.setServerLanguageCode("zh");            // 登录ftp            ftp.login(userName, passWord);            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {                ftp.disconnect();                System.out.println("连接服务器失败");            }            System.out.println("登陆服务器成功");        } catch (IOException e) {            e.printStackTrace();        }        return ftp;    }    /**     * 关闭连接-FTP方式     *      * @param ftp     *            FTPClient对象     * @return boolean     */    public static boolean closeFTP(FTPClient ftp) {        if (ftp.isConnected()) {            try {                ftp.disconnect();                System.out.println("ftp已经关闭");                return true;            } catch (Exception e) {                e.printStackTrace();            }        }        return false;    }    /**     * 上传文件-FTP方式     *      * @param ftp     *            FTPClient对象     * @param path     *            FTP服务器上传地址     * @param filename     *            本地文件路径     * @param inputStream     *            输入流     * @return boolean     */    public static boolean uploadFile(FTPClient ftp, String path,            String fileName, InputStream inputStream) {        boolean success = false;        try {            ftp.changeWorkingDirectory(path);// 转移到指定FTP服务器目录            FTPFile[] fs = ftp.listFiles();// 得到目录的相应文件列表            fileName = FTPHelper.changeName(fileName, fs);            fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");            path = new String(path.getBytes("GBK"), "ISO-8859-1");            // 转到指定上传目录            ftp.changeWorkingDirectory(path);            // 将上传文件存储到指定目录            ftp.setFileType(FTP.BINARY_FILE_TYPE);            // 如果缺省该句 传输txt正常 但图片和其他格式的文件传输出现乱码            ftp.storeFile(fileName, inputStream);            // 关闭输入流            inputStream.close();            // 退出ftp            ftp.logout();            // 表示上传成功            success = true;            System.out.println("上传成功。。。。。。");        } catch (Exception e) {            e.printStackTrace();        }        return success;    }    /**     * 删除文件-FTP方式     *      * @param ftp     *            FTPClient对象     * @param path     *            FTP服务器上传地址     * @param filename     *            FTP服务器上要删除的文件名     * @return     */    public static boolean deleteFile(FTPClient ftp, String path, String fileName) {        boolean success = false;        try {            ftp.changeWorkingDirectory(path);// 转移到指定FTP服务器目录            fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");            path = new String(path.getBytes("GBK"), "ISO-8859-1");            ftp.deleteFile(fileName);            ftp.logout();            success = true;        } catch (Exception e) {            e.printStackTrace();        }        return success;    }    /**     * 上传文件-FTP方式     *      * @param ftp     *            FTPClient对象     * @param path     *            FTP服务器上传地址     * @param fileName     *            本地文件路径     * @param localPath     *            本里存储路径     * @return boolean     */    public static boolean downFile(FTPClient ftp, String path, String fileName,            String localPath) {        boolean success = false;        try {            ftp.changeWorkingDirectory(path);// 转移到FTP服务器目录            FTPFile[] fs = ftp.listFiles(); // 得到目录的相应文件列表            for (FTPFile ff : fs) {                if (ff.getName().equals(fileName)) {                    File localFile = new File(localPath + "\\" + ff.getName());                    OutputStream outputStream = new FileOutputStream(localFile);                    // 将文件保存到输出流outputStream中                    ftp.retrieveFile(new String(ff.getName().getBytes("GBK"),                            "ISO-8859-1"), outputStream);                    outputStream.flush();                    outputStream.close();                    System.out.println("下载成功");                }            }            ftp.logout();            success = true;        } catch (Exception e) {            e.printStackTrace();        }        return success;    }    /**     * 判断是否有重名文件     *      * @param fileName     * @param fs     * @return     */    public static boolean isFileExist(String fileName, FTPFile[] fs) {        for (int i = 0; i < fs.length; i++) {            FTPFile ff = fs[i];            if (ff.getName().equals(fileName)) {                return true; // 如果存在返回 正确信号            }        }        return false; // 如果不存在返回错误信号    }    /**     * 根据重名判断的结果 生成新的文件的名称     *      * @param fileName     * @param fs     * @return     */    public static String changeName(String fileName, FTPFile[] fs) {        int n = 0;        // fileName = fileName.append(fileName);        while (isFileExist(fileName.toString(), fs)) {            n++;            String a = "[" + n + "]";            int b = fileName.lastIndexOf(".");// 最后一出现小数点的位置            int c = fileName.lastIndexOf("[");// 最后一次"["出现的位置            if (c < 0) {                c = b;            }            StringBuffer name = new StringBuffer(fileName.substring(0, c));// 文件的名字            StringBuffer suffix = new StringBuffer(fileName.substring(b + 1));// 后缀的名称            fileName = name.append(a) + "." + suffix;        }        return fileName.toString();    }    /**     * 判断两个集合是否相同     *      * @param list1     * @param list2     * @return     */    public static boolean equalList(List list1, List list2) {        return (list1.size() == list2.size()) && list1.containsAll(list2);    }    /**     * 判断两个集合的不同值(只限于strlist)     *      * @param list1     * @param list2     */    public static List<String> getUncontain(List<String> ftpList,            List<String> localDirList) {        List<String> tempList = new ArrayList<String>();        for (String str1 : ftpList) {            if (!localDirList.contains(str1)) {                // list2中不包含str1                tempList.add(str1);            }        }        return tempList;    }    /**     * 判断两个集合的不同值     *      * @param list1     * @param list2     */    public static List<String> getUncontain(ArrayList<ImageItem> listA,            List<ImageItem> listB) {        ArrayList<ImageItem> listC = (ArrayList<ImageItem>) listA.clone();        ArrayList<String> strListC =  new ArrayList<String>();        ArrayList<String> strListB =  new ArrayList<String>();        for (ImageItem str : listC) {            strListC.add(str.getFileName());        }        for (ImageItem str : listB) {            strListB.add(str.getFileName());        }        System.out.println("c " + listC);        strListC.removeAll(strListB);        return strListC;    }    /**     * 判断两个集合的不同值     *      * @param list1     * @param list2     */    public static List<String> getUncontain2(ArrayList<ImageItem> listA,            List<ImageItem> listB) {        ArrayList<ImageItem> listC = (ArrayList<ImageItem>) listA.clone();        ArrayList<String> strListC =  new ArrayList<String>();        ArrayList<String> strListB =  new ArrayList<String>();        for (ImageItem str : listC) {            strListC.add(str.getFileName());        }        for (ImageItem str : listB) {            strListB.add(str.getFileName());        }        System.out.println("c " + listC);        strListC.removeAll(strListB);        return strListC;    }    /**     * 下载单个文件,可实现断点下载.     *      * @param serverPath     *            Ftp目录及文件路径     * @param localPath     *            本地目录     * @param fileName     *            下载之后的文件名称     * @param listener     *            监听器     * @throws IOException     */    public static void downloadSingleFile(FTPClient ftpClient,String serverPath, String localPath,            String fileName, FtpProgressListener listener) throws Exception {        listener.onFtpProgress(Constant.FTP_CONNECT_SUCCESS, 0, null);        // 先判断服务器文件是否存在        FTPFile[] files = ftpClient.listFiles(serverPath);        if (files.length == 0) {            listener.onFtpProgress(Constant.FTP_FILE_NOTEXISTS, 0, null);            return;        }        // 创建本地文件夹        File mkFile = new File(localPath);        if (!mkFile.exists()) {            mkFile.mkdirs();        }        localPath = localPath + fileName;        // 接着判断下载的文件是否能断点下载        long serverSize = files[0].getSize(); // 获取远程文件的长度        File localFile = new File(localPath);        long localSize = 0;        if (localFile.exists()) {            localSize = localFile.length(); // 如果本地文件存在,获取本地文件的长度            if (localSize >= serverSize) {                File file = new File(localPath);                file.delete();            }        }        // 进度        long step = serverSize / 100;        long process = 0;        long currentSize = 0;        // 开始准备下载文件        OutputStream out = new FileOutputStream(localFile, true);        ftpClient.setRestartOffset(localSize);        InputStream input = ftpClient.retrieveFileStream(serverPath);        byte[] b = new byte[1024];        int length = 0;        while ((length = input.read(b)) != -1) {            out.write(b, 0, length);            currentSize = currentSize + length;            if (currentSize / step != process) {                process = currentSize / step;                if (process % 5 == 0) { // 每隔%5的进度返回一次                    listener.onFtpProgress(Constant.FTP_DOWN_LOADING, process,                            null);                }            }        }        out.flush();        out.close();        input.close();        // 此方法是来确保流处理完毕,如果没有此方法,可能会造成现程序死掉        if (ftpClient.completePendingCommand()) {            listener.onFtpProgress(Constant.FTP_DOWN_SUCCESS, 0, new File(                    localPath));        } else {            listener.onFtpProgress(Constant.FTP_DOWN_FAIL, 0, null);        }        // 下载完成之后关闭连接        closeFTP(ftpClient);        listener.onFtpProgress(Constant.FTP_DISCONNECT_SUCCESS, 0, null);        return;    }    /*     * 进度监听器     */    public interface FtpProgressListener {        /**         *          * @Description TODO FTP 文件长传下载进度触发         * @param currentStatus         *            当前FTP状态         * @param process         *            当前进度         * @param targetFile         *            目标文件         */        public void onFtpProgress(int currentStatus, long process,                File targetFile);    }

“`
/**
*
* @author derik
*
*/
public class FTPConstant {

public static final String userName = "root";public static final String password = "root";public static final String url = "192.168.1.251";public static final int port = 21;public static final String fileName = AppUtil.createName(System.currentTimeMillis());public static final String localPath  = FileUtil.getNuctechPath();// 本地路径;public static final String remotePath = "/mnt/660010F011"; //FTP远程文件夹目录public static final int DELETE_ITEM = 001; //FTP通信public FTPConstant(int type, String message) {    this.type = type; // 不同消息的区分    this.message = message;}public int type;private String message;public String getMessage() {    return message;}public void setMessage(String message) {    this.message = message;}

就这么多就可以实现了 ,展示列表那一部分在下一篇文章中讲解
其中涉及到listview长按删除、点击跳转预览页面 使用的是Fragment+viewpager

第一次写博客,写的比较乱,有什么不明白的地方,尽情留言
微信 derikli123
QQ 85815924

阅读全文
2 0
原创粉丝点击