NDK開發(七) :JNI實現文件夾遍歷

轉載請以連接形式標明出處: 本文出自:103style的博客java

本文操做以 Android Studio 3.4.2 版本爲例android


NDK開發文章彙總git


編寫測試代碼

  • 建立類 JniListDirAllFiles,編寫對應的測試代碼:
    public class JniListDirAllFiles {
        static {
            System.loadLibrary("list_dir_all_file");
        }
        /**
         * 輸出文件夾下得全部文件
         *
         * @param dirPath 文件夾路徑
         */
        public native void listDirAllFile(String dirPath);
    
        public void test() {
            listDirAllFile(Config.BASE_URL);
        }
    }
    複製代碼
  • 建立list_dir_all_file.cpp.
  • 添加如下代碼到CMakeLists.txt
    add_library(
            list_dir_all_file
            SHARED
            list_dir_all_file.cpp)
    target_link_libraries(
            list_dir_all_file
            ${log-lib})
    複製代碼

實現JNI文件夾遍歷邏輯

#include <jni.h>
#include <dirent.h>
#include <string>
#include <android/log.h>
#include "LogUtils.h"

const int PATH_MAX_LENGTH = 256;

extern "C"
JNIEXPORT void JNICALL
Java_com_lxk_ndkdemo_JniListDirAllFiles_listDirAllFile(JNIEnv *env, jobject instance,
                                                       jstring dirPath_) {
    //空判斷
    if (dirPath_ == nullptr) {
        LOGE("dirPath is null!");
        return;
    }
    const char *dirPath = env->GetStringUTFChars(dirPath_, nullptr);
    //長度判讀
    if (strlen(dirPath) == 0) {
        LOGE("dirPath length is 0!");
        return;
    }
    //打開文件夾讀取流
    DIR *dir = opendir(dirPath);
    if (nullptr == dir) {
        LOGE("can not open dir, check path or permission!")
        return;
    }

    struct dirent *file;
    while ((file = readdir(dir)) != nullptr) {
        //判斷是否是 . 或者 .. 文件夾
        if (strcmp(file->d_name, ".") == 0 || strcmp(file->d_name, "..") == 0) {
            LOGV("ignore . and ..");
            continue;
        }

        if (file->d_type == DT_DIR) {
            //是文件夾則遍歷
            //構建文件夾路徑
            char *path = new char[PATH_MAX_LENGTH];
            memset(path, 0, PATH_MAX_LENGTH);
            strcpy(path, dirPath);
            strcat(path, "/");
            strcat(path, file->d_name);
            jstring tDir = env->NewStringUTF(path);
            //讀取指定文件夾
            Java_com_lxk_ndkdemo_JniListDirAllFiles_listDirAllFile(env, instance, tDir);
            //釋放文件夾路徑內存
            free(path);
        } else {
            //打印文件名
            LOGD("%s/%s", dirPath, file->d_name);
        }
    }

    //關閉讀取流
    closedir(dir);

    env->ReleaseStringUTFChars(dirPath_, dirPath);
}
複製代碼

執行測試代碼

private void testListDirAllFiles() {
    if (hasFilePermission()) {
        new JniListDirAllFiles().test();
        Toast.makeText(this, "任務完成,檢查看日誌輸出", Toast.LENGTH_SHORT).show();
    }
}
複製代碼

會在控制檯打印/storage/emulated/0/NDKDemo/目錄下的全部文件。github


Demo地址:https://github.com/103style/NDKDoc/tree/master/NDKDemobash

若是以爲不錯的話,請幫忙點個讚唄。app

以上測試


掃描下面的二維碼,關注個人公衆號 Android1024, 點關注,不迷路。 ui

Android1024
相關文章
相關標籤/搜索