df-helper 0.2.26

df helper tools db cache
Documentation
use std::fs;
use std::fs::remove_file;
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();
        }
    }
}

/// 获取文件内容
pub fn file_content_get_stream(path: &str) -> String {
    let file = fs::read(path).unwrap();
    let contents = unsafe { String::from_utf8_unchecked(file) };
    contents
}


/// 获取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 file_content_put_u8(path: &str, data: Vec<u8>) -> 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();
}

/// 删除文件
pub fn remove(path: &str) -> bool {
    let res = remove_file(path);
    match res {
        Ok(_) => {
            true
        }
        Err(e) => {
            println!("remove file error:{}", e);
            false
        }
    }
}