加入下方官方优快云班级,得鸿蒙礼盒
本期活动时间:2025年8月1日-12月31日
问题现象
如何在应用沙箱内新建文件或者文件夹呢?使用fs.statSync(path)过程中会产生No such file or directory的错误,该怎么处理呢?

背景知识
- fs.statSync:以同步方法获取文件或者目录的详细属性信息。
- fs.access:检查文件或者目录是否存在。
- fs.mkdir:创建目录。
- fs.open:打开文件,可设置打开文件的选项。
- fs.read:从文件读取数据。
- fs.write:将数据写入文件。
解决方案
开发者在创建文件前希望判断指定的文件夹是否存在,但是是使用fs.statSync(path)的返回值stat.isDirectory()来判断。然而,直接使用statSync方法并不合适,因为该方法返回的是文件或文件夹的详细属性及类型,并不能判断文件是否存在。并且指定路径并非沙箱路径或者该方法的参数不为已打开的文件描述符fd,就会抛出“No such file or directory”的异常。
依据相关背景知识,相关操作通过以下方式实现:
1.使用fs.access判断文件/目录是否存在。
2.使用fs.mkdir创建文件夹。
3.使用fs.open(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE)创建文件并以读写模式打开。
4.文件读写则使用fs.read、fs.write方法。
import { fileIo as fs } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { buffer } from '@kit.ArkTS';
@Entry
@Component
struct Index {
@State path: string = ''
aboutToAppear(): void {
this.path = `${this.getUIContext().getHostContext()!.filesDir}/testDir`
}
createFolder() {
let isExist = fs.accessSync(this.path, fs.AccessModeType.EXIST)
if (isExist) {
this.getUIContext()
.getPromptAction()
.showToast({ message: '文件夹已存在', alignment: Alignment.Center, duration: 1500 })
return
}
fs.mkdir(this.path).then(() => {
this.getUIContext()
.getPromptAction()
.showToast({ message: '成功新建文件夹', alignment: Alignment.Center, duration: 1500 })
console.info('mkdir succeed');
}).catch((err: BusinessError) => {
this.getUIContext()
.getPromptAction()
.showToast({ message: `新建文件夹失败:${err.message}`, alignment: Alignment.Center, duration: 1500 })
console.error('mkdir failed with error message: ' + err.message + ', error code: ' + err.code);
});
}
async createFile() {
try {
let isExist = fs.accessSync(this.path, fs.AccessModeType.EXIST)
if (!isExist) {
await fs.mkdir(this.path)
}
// 获取应用沙箱路径
const filePath = `${this.path}/example.txt`;
const file = await fs.open(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
const text = 'HelloWorld';
await fs.write(file.fd, text);
await fs.close(file.fd);
console.info('文件保存成功,路径:', filePath);
this.getUIContext()
.getPromptAction()
.showToast({ message: '新建文本文件', alignment: Alignment.Center, duration: 1500 })
} catch (err) {
console.error('保存文件失败:', err);
this.getUIContext()
.getPromptAction()
.showToast({ message: '新建文本文件失败', alignment: Alignment.Center, duration: 1500 })
}
}
async readFile() {
const filePath = `${this.path}/example.txt`;
let isExist = fs.accessSync(filePath, fs.AccessModeType.EXIST)
if (!isExist) {
this.getUIContext()
.getPromptAction()
.showToast({ message: '文件不存在', alignment: Alignment.Center, duration: 1500 })
return
}
const file = await fs.open(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
let arrayBuffer = new ArrayBuffer(4096);
await fs.read(file.fd, arrayBuffer)
this.getUIContext().getPromptAction().showToast({
message: buffer.from(arrayBuffer).toString('utf-8'),
alignment: Alignment.Center,
duration: 1500
})
}
build() {
Row() {
Column({ space: 10 }) {
Button('新建文件夹')
.fontSize(20)
.fontWeight(FontWeight.Bold)
.onClick(() => {
this.createFolder()
})
Button('新建文件')
.fontSize(20)
.fontWeight(FontWeight.Bold)
.onClick(() => {
this.createFile()
})
Button('读取文件')
.fontSize(20)
.fontWeight(FontWeight.Bold)
.onClick(() => {
this.readFile()
})
}
.width('100%')
}
.height('100%')
}
}
常见FAQ
Q:是否支持创建多文件夹?
A:可以使用fs.mkdir创建目录,使用callback异步回调。当参数recursion指定为true时,可递归创多文件夹。
4008

被折叠的 条评论
为什么被折叠?



