栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android 9.0 自定义服务(三)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android 9.0 自定义服务(三)

ftp 服务工具类
  • 代码路径:
  • 1. ftp 连接
  • 2. ftp 下载
  • 3. ftp 上传
  • 4. ftp 断开

代码路径:

frameworks/base/services/core/java/com/android/server/FtpUtils.java

1. ftp 连接
   public boolean ftpConnect(String host, String username, String password, int port) {
       try {
           if (ftpClient == null)
               ftpClient = new FTPClient();
           if (ftpClient.isConnected()) {
               ftpClient.disconnect();
           }
           ftpClient.setDataTimeout(20000);// 设置连接超时时间
           ftpClient.setControlEncoding("utf-8");
           Log.d(TAG, "connecting to the ftp server " host " :" port);
           ftpClient.connect(host, port);
           // 根据返回的状态码,判断链接是否建立成功
           if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
               Log.d(TAG, "login to the ftp server");
               boolean status = ftpClient.login(username, password);
               Log.d(TAG, "status = " status);
               
               ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
               ftpClient.enterLocalPassiveMode();
               return status;
           }
       } catch (Exception e) {
           e.printStackTrace();
           Log.d(TAG, "Error: could not connect to host " host);
       }
       return false;
   }
2. ftp 下载
   // ftpFilePath -> /test/update.zip
   // downPath -> /data/update.zip
   public boolean downLoadFile(String ftpFilePath, String downPath) {
        if (ftpClient == null) {
            return false;
        }
        // 默认失败
        boolean flag = false;
        FTPFile[] files;
        // 跳转到文件目录
        try {
            // 获取目录下文件集合
            ftpClient.enterLocalPassiveMode();
            Log.d(TAG, "ftpFilePath = " + ftpFilePath);
            files = ftpClient
                    .listFiles(new String(ftpFilePath.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        } catch (IOException e) {
            Log.e(TAG, "downLoadFTP: " + e);
            e.printStackTrace();
            return false;
        }

        if (files != null && files.length >= 1) {
            long lRemoteSize = files[0].getSize();
            File downFile = new File(downPath);
            FileOutputStream fos = null;
            InputStream in = null;
            try {
                fos = new FileOutputStream(downFile);
                in = ftpClient.retrieveFileStream(
                        new String(ftpFilePath.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
                Log.d(TAG, "file name = "
                        + new String(files[0].getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)
                        + " ,in.available() = " + in.available());
                byte[] bytes = new byte[1024 * 4];
                long step = lRemoteSize / 100;
                long process = 0;
                long localSize = 0L;
                int c = -1;
                while ((c = in.read(bytes)) != -1) {
                    fos.write(bytes, 0, c);
                    // android.util.Log.d(TAG,"c = " + c);
                    fos.flush();
                    localSize += c;
                    long nowProcess = localSize / step;
                    if (nowProcess > process) {
                        process = nowProcess;
                        android.util.Log.d(TAG, "downloaded nowProcess = " + nowProcess);
                        if (mCallback != null) {
                            mCallback.onProgress(nowProcess);
                        }
                    }
                }

                in.close();
                fos.close();
                flag = ftpClient.completePendingCommand();
                if (mCallback != null) {
                    if (flag) {
                        mCallback.onSuccess();
                    } else {
                        mCallback.onFailed();
                    }
                }
            } catch (Exception e) {
                android.util.Log.d(TAG, "downloaded failed ");
                e.printStackTrace();
                try {
                    if (mCallback != null) {
                        mCallback.onFailed();
                    }
                } catch (Exception exception) {
                    // TODO: handle exception
                    exception.printStackTrace();
                }
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            Log.e(TAG, "the file is not exist");
            try {
                if (mCallback != null) {
                    mCallback.onFailed();
                }
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
        return flag;
    }
3. ftp 上传
   // srcFilePath ->  /data/targer/ or /data/targer/1.txt
   // ftpPath -> /test/
   public boolean uploadFile(String srcFilePath, String ftpPath) {
        boolean flag = false;
        InputStream in = null;
        try {
            // 上传文件
            File file = new File(srcFilePath);
            if (!file.exists()) {
                Log.d(TAG, "local file not exists");
                return false;
            }

            // 设置PassiveMode传输
            ftpClient.enterLocalPassiveMode();
            // 设置二进制传输,使用BINARY_FILE_TYPE,ASC容易造成文件损坏
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            // 判断FPT目标文件夹时候存在不存在则创建
            if (!ftpClient.changeWorkingDirectory(ftpPath)) {
                Log.d(TAG, " makeDirectory ");
                ftpClient.makeDirectory(ftpPath);
            }
            Log.d(TAG, " changeWorkingDirectory ");
            // 跳转目标目录
            ftpClient.changeWorkingDirectory(ftpPath);

            if (file.isDirectory()) {
                // 上传文件夹
                flag = uploadDirectory(srcFilePath, ftpPath);
            } else {
                // 上传单个文件
                in = new FileInputStream(file);
                String tempName = ftpPath + File.separator + file.getName();
                flag = ftpClient.storeFile(
                        new String(tempName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1),
                        in);
                if (flag) {
                    Log.d(TAG, "upload file success");
                } else {
                    Log.e(TAG, "upload file failed");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "upload failed");
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

    private boolean uploadingMany(File localFile, String ftpPath) throws IOException {
        BufferedInputStream inStream = null;
        boolean success = false;
        try {
            ftpClient.changeWorkingDirectory(ftpPath);// 改变工作路径
            inStream = new BufferedInputStream(new FileInputStream(localFile));
            Log.d(TAG, "start upload file.....");
            success = this.ftpClient.storeFile(localFile.getName(), inStream);
            if (success == true) {
                Log.d(TAG, localFile.getName() + "upload file success");
                return success;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.d(TAG, localFile.getName() + "file not found!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }

    public boolean uploadDirectory(String localDirectory,
            String remoteDirectoryPath) {
        File src = new File(localDirectory);
        try {
            remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
            boolean makeDirFlag = ftpClient.makeDirectory(remoteDirectoryPath);
            Log.d(TAG, "localDirectory : " + localDirectory);
            Log.d(TAG, "remoteDirectoryPath : " + remoteDirectoryPath);
            Log.d(TAG, "src.getName() : " + src.getName());
            Log.d(TAG, "makeDirFlag : " + makeDirFlag);
            // ftpClient.listDirectories();
        } catch (IOException e) {
            e.printStackTrace();
            Log.d(TAG, remoteDirectoryPath + " create Direction failed!");
        }
        File[] allFile = src.listFiles();
        for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
            if (!allFile[currentFile].isDirectory()) {
                String srcName = allFile[currentFile].getPath().toString();
                try {
                    uploadingMany(new File(srcName), remoteDirectoryPath);
                } catch (IOException e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
        }
        for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
            if (allFile[currentFile].isDirectory()) {
                // 递归上传
                uploadDirectory(allFile[currentFile].getPath().toString(),
                        remoteDirectoryPath);
            }
        }
        return true;
    }
4. ftp 断开
    public boolean ftpDisconnect() {
        // 判断空指针
        if (ftpClient == null) {
            return true;
        }

        // 断开ftp服务器连接
        try {
            ftpClient.logout();
            ftpClient.disconnect();
            return true;
        } catch (Exception e) {
            Log.d(TAG, "Error occurred while disconnecting from ftp server.");
        }
        return false;
    }

添加的服务接口没有全部实现,主要就是这么几个

暑期编程PK赛 得CSDN机械键盘等精美礼品!
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1016532.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号