介绍
本文介绍 ohos.file.fs 读写文本文件
导包
import { fileIo as fs } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
错误码
下面很多操作中,会抛出异常,异常信息中包含错误码,详见 链接
打开创建文件、关闭连接
详见 链接
写入文本
同步
以同步方法将数据写入文件。
writeSync(fd: number, buffer: ArrayBuffer | string, options?: WriteOptions): number
参数:
fd:
number类型,必填,已打开的文件描述符。buffer:
ArrayBuffer | string类型,必填,待写入文件的数据,可来自缓冲区或字符串。options:
WriteOptions类型,支持如下选项:offset,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。
length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度。
encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 ‘utf-8’。当前仅支持 ‘utf-8’。
返回值:number 类型,返回实际写入的数据长度(单位:字节)。
例子
let filePath = pathDir + "/test.txt";
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let str: string = "hello, world";
let writeLen = fs.writeSync(file.fd, str);
console.info("write data to file succeed and size is:" + writeLen);
fs.closeSync(file);
异步
将数据写入文件,使用promise异步回调。
write(fd: number, buffer: ArrayBuffer | string, options?: WriteOptions): Promise<number>
参数:同上
返回值: Promise<number> 类型,Promise对象。返回实际写入的数据长度(单位:字节)。
读取文本
同步
以同步方法基于文本方式读取文件(即直接读取文件的文本内容)。
readTextSync(filePath: string, options?: ReadTextOptions): string
参数:
filePath:
string类型,必填,文件的应用沙箱路径。options:
ReadTextOptions类型,支持如下选项:offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读取。
length,number类型,表示期望读取数据的长度。可选,默认文件长度。
encoding,string类型,当数据是 string 类型时有效,表示数据的编码方式,默认 ‘utf-8’,仅支持 ‘utf-8’。
返回值:string 类型,返回读取文件的内容。
异步
基于文本方式读取文件(即直接读取文件的文本内容),使用promise异步回调。
readText(filePath: string, options?: ReadTextOptions): Promise<string>
参数:同上
返回值: Promise<string>,Promise对象。返回读取文件的内容。
例子
import { BusinessError } from '@kit.BasicServicesKit';
let filePath = pathDir + "/test.txt";
fs.readText(filePath).then((str: string) => {
console.info("readText succeed:" + str);
}).catch((err: BusinessError) => {
console.error("readText failed with error message: " + err.message + ", error code: " + err.code);
});
例子
import { fileIo as fs } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
/**
* 文件路径
*/
filePath:string = '';
build() {
// 列示布局
Column() {
Button("写入文件")
.onClick(() => {
const pathDir = getContext().cacheDir;
this.filePath = pathDir + "/test.txt";
let file = fs.openSync(this.filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let str: string = "hello, world";
let writeLen = fs.writeSync(file.fd, str);
console.info("write data to file succeed and size is:" + writeLen);
fs.closeSync(file);
})
Button("读取文件")
.onClick(() => {
if(fs.accessSync(this.filePath)){
let str2 = fs.readTextSync(this.filePath);
console.info("-----读取内容:" + str2);
}else{
console.error("----","文件不存在")
}
})
}
}
}