baichun_framework_core/utils/
file.rs

1use std::path::Path;
2
3use crate::error::{Error, Result};
4
5/// 文件工具
6pub struct FileUtils;
7
8impl FileUtils {
9    /// 获取文件扩展名
10    pub fn get_extension(path: impl AsRef<Path>) -> Option<String> {
11        path.as_ref()
12            .extension()
13            .and_then(|ext| ext.to_str())
14            .map(|s| s.to_lowercase())
15    }
16
17    /// 获取文件名(不含扩展名)
18    pub fn get_stem(path: impl AsRef<Path>) -> Option<String> {
19        path.as_ref()
20            .file_stem()
21            .and_then(|stem| stem.to_str())
22            .map(|s| s.to_string())
23    }
24
25    /// 获取文件名(含扩展名)
26    pub fn get_filename(path: impl AsRef<Path>) -> Option<String> {
27        path.as_ref()
28            .file_name()
29            .and_then(|name| name.to_str())
30            .map(|s| s.to_string())
31    }
32
33    /// 检查文件是否存在
34    pub fn exists(path: impl AsRef<Path>) -> bool {
35        path.as_ref().exists()
36    }
37
38    /// 检查是否为文件
39    pub fn is_file(path: impl AsRef<Path>) -> bool {
40        path.as_ref().is_file()
41    }
42
43    /// 检查是否为目录
44    pub fn is_dir(path: impl AsRef<Path>) -> bool {
45        path.as_ref().is_dir()
46    }
47
48    /// 创建目录(递归)
49    pub fn create_dir_all(path: impl AsRef<Path>) -> Result<()> {
50        std::fs::create_dir_all(path.as_ref()).map_err(Error::from)
51    }
52
53    /// 删除文件
54    pub fn remove_file(path: impl AsRef<Path>) -> Result<()> {
55        std::fs::remove_file(path.as_ref()).map_err(Error::from)
56    }
57
58    /// 删除目录(递归)
59    pub fn remove_dir_all(path: impl AsRef<Path>) -> Result<()> {
60        std::fs::remove_dir_all(path.as_ref()).map_err(Error::from)
61    }
62
63    /// 获取文件大小
64    pub fn get_size(path: impl AsRef<Path>) -> Result<u64> {
65        std::fs::metadata(path.as_ref())
66            .map(|meta| meta.len())
67            .map_err(Error::from)
68    }
69
70    /// 获取文件修改时间
71    pub fn get_modified_time(path: impl AsRef<Path>) -> Result<std::time::SystemTime> {
72        std::fs::metadata(path.as_ref())
73            .map(|meta| meta.modified().unwrap())
74            .map_err(Error::from)
75    }
76}