JNI 檔案遍歷

aabbcc又一年發表於2020-12-24

1.引入#include "dirent.h"
2.相關結構體
(1)DIR

struct DIR {
        struct dirent ent;
        struct _WDIR *wdirp;
    };
    typedef struct DIR DIR;

(2)dirent

 struct dirent {
        long d_ino;     /* Always zero */
        unsigned short d_reclen;  /* Structure size */
        size_t d_namlen;    /* Length of name without \0 */
        int d_type;   /* File type */
        char d_name[PATH_MAX];     /* File name */
    };
    typedef struct dirent dirent;

2.c++遍歷檔案

void showAllFiles(string dir_name) {
    if (dir_name.empty()) {
        LOGE("dir_name is null !");
        return;
    }
    DIR *dir = opendir(dir_name.c_str());
    if (NULL == dir) {
        LOGE("Can not open dir,Check path or permission!");
        return;
    }
    dirent *file;
    while ((file = readdir(dir)) != NULL) {    //類似BufferedReader.readLine(),不過這裡返回是dirnet*,不是string
        if (file->d_type == DT_DIR) {   //是目錄則遞迴
            string filePath = dir_name + "/" + file->d_name;
            showAllFiles(filePath);
        } else {                            //是檔案則輸出檔名
            LOGE("filePath:%s%s", dir_name.c_str(), file->d_name);
        }
    }
    closedir(dir);   //opendir(char* dir)後要closedir(DIR *dir )
}

3.java變數檔案,這裡篩選目錄下的所以txt檔案

    fun showJavaAllFiels(path:String){
        var file: File = File(path)
        if(file.exists()){
            for(fileitm in file.listFiles()){
                if (fileitm.isFile){
                    if(fileitm.name.endsWith(".txt"))
                        Log.e("native",path+"/"+fileitm.name)
                }else{
                    showJavaAllFiels(path+"/"+fileitm.name)
                }
            }
        }else{
            Log.e("native","file is not exit!")
        }
    }

4.讀取txt檔案

 fun readTxtFile(path:String){
        var file = File(path)
        if(file.exists()){
            try {
                //InputStream 是位元組輸入流的所有類的超類,一般我們使用它的子類,如FileInputStream等.
                //OutputStream是位元組輸出流的所有類的超類,一般我們使用它的子類,如FileOutputStream等.
                var fileInPutString = FileInputStream(file)
                //InputStreamReader 是位元組流通向字元流的橋樑,它將位元組流轉換為字元流.
                //OutputStreamWriter是字元流通向位元組流的橋樑,它將字元流轉換為位元組流.
                var inputStreamReader = InputStreamReader(fileInPutString)
                //BufferedReader從字元輸入流中讀取文字,緩衝各個字元
                //BufferedWriter將文字寫入字元輸出流,緩衝各個字元
                var bufferReader = BufferedReader(inputStreamReader)
                var txt:String =""
                var i= 0
                while (bufferReader.readLine()?.also { txt = it }!=null){
                    i++;
                    Log.e("txt",i.toString()+txt)
                }
                bufferReader.close()
                inputStreamReader.close()
                fileInPutString.close()
            }catch (e:IOException){
            }
        }
    }

5.also擴充套件函式是和let相同,函式體內使用it代表呼叫物件object,不同點是返回值是當前物件,let返回的是最後一行或指定的return表示式。?.also{}表示object不為null才會執行函式體。

相關文章