1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use std::fs;
use std::path::Path;
use json::{JsonValue, object};

/// 创建目录
///
/// * path 路径带文件名 /home/roger/foo/bar/baz.txt
pub fn create_dir(path: &str) -> bool {
    let path = Path::new(path);
    let prefix = path.parent().unwrap();
    let data = fs::create_dir_all(prefix);
    match data {
        Ok(_e) => {
            return true;
        }
        Err(_e) => {
            return false;
        }
    }
}

/// 获取文件夹下的文件列表
pub fn dir_files(path: &str) -> Vec<String> {
    let mut files = vec![];
    for entry in walkdir::WalkDir::new(path) {
        match entry {
            Ok(e) => {
                if e.path().is_dir() {
                    continue;
                }
                files.push(e.path().display().to_string())
            }
            _ => {}
        }
    }
    return files;
}


/// 获取文件内容
pub fn file_content_get(path: &str) -> String {
    let data = fs::read_to_string(path);
    match data {
        Ok(content) => {
            return content;
        }
        Err(e) => {
            println!("{}", e);
            return "".to_string();
        }
    }
}

/// 获取JSON文件内容
pub fn file_content_get_json(path: &str) -> JsonValue {
    if !is_file(path) {
        return object! {};
    }
    let data = file_content_get(path);
    if data == "" {
        return object! {};
    }
    json::parse(data.as_str()).unwrap()
}

/// 写入文件内容
pub fn file_content_put(path: &str, data: &str) -> bool {
    create_dir(path);
    let data = fs::write(path, data);
    match data {
        Ok(_e) => {
            return true;
        }
        Err(e) => {
            println!("{}", e);
            return false;
        }
    }
}

/// 判断文件是否存在
pub fn is_file(file: &str) -> bool {
    let o = Path::new(file);
    return o.is_file();
}