文件操作是App研发过程常见的操作,通常不同业务功能中的文件会放到不同的目录中,在不同的业务功能中进行管理,下面的代码示例实现了在沙盒文件中生成子目录的能力,支持指定多级子目录。
javascript
function getRootDirPath(context: Context,subDir:string): string|null {
const rootDirPath: string = context.filesDir + subDir
let rootDirExist = false
try {
rootDirExist = fs.accessSync(rootDirPath);
if (rootDirExist) {
return rootDirPath;
} else {
fs.mkdirSync(rootDirPath, true);
rootDirExist = fs.accessSync(rootDirPath);
if (rootDirExist) {
return rootDirPath;
} else {
return null;
}
}
} catch (err) {
return null
}
return rootDirPath;
}
使用代码示例
javascript
let dirPath = getRootDirPath(context,"/maodou/image/"); //可以是多级目录
if (dirPath) {
let fileName = dirPath + "xxx.png"
}