HarmonyOS鸿蒙Next中使用fs.writeSync貌似没有成功的问题
HarmonyOS鸿蒙Next中使用fs.writeSync貌似没有成功的问题
创建文件写入信息函数:
export function createFile(){ //获取应用文件路径
let context = getContext(this) as common.UIAbilityContext
let filesDir = context.filesDir
let filesDir1 = context.distributedFilesDir
let context1 = getContext(this).getApplicationContext()
let f1 = context1.filesDir
let context2 = getContext(this) as common.AbilityStageContext
let f2 = context2.filesDir
let context3 = getContext(this) as common.ExtensionContext
let f3 = context3.filesDir
//新建并打开文件
let file = fs.openSync(filesDir + '/test666.txt',fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
//写入一段内容至文件
let writeLen = fs.writeSync(file.fd,"Try to write str.")
console.log("the length of str is:" + writeLen)
// 从文件读取一段内容
let buf = new ArrayBuffer(1024)
let readLen = fs.readSync(file.fd,buf,{offset : 0})
console.log("the content of file:" + String.fromCharCode.apply(null,new Uint8Array(buf.slice(0,readLen))))
//关闭文件
fs.close(file);}
读写函数
export function readWriteFile(){ // 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext;
let fileDir = context.filesDir;
//打开文件
let srcFile = fs.openSync(fileDir + '/test666.txt',fs.OpenMode.READ_WRITE);
let destFile = fs.openSync(fileDir + '/destFile.txt',fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
//读取源文件内容并写入至目的文件
let buffSize = 4096;
let readSize = 0;
let buf = new ArrayBuffer(buffSize);
let readLen = fs.readSync(srcFile.fd,buf,{offset:readSize})
console.log("the content of file 111:" + String.fromCharCode.apply(null,new Uint8Array(buf.slice(0,readLen))))
while (readLen > 0){
readSize += readLen;
fs.writeSync(destFile.fd,buf);
readLen = fs.readSync(destFile.fd,buf,{offset:0});
readLen = fs.readSync(srcFile.fd,buf,{offset:readSize});
}
//打印写入文件的信息
readLen = fs.readSync(destFile.fd,buf,{offset : 0})
console.log("the content of file 333:" + String.fromCharCode.apply(null,new Uint8Array(buf.slice(0,readLen))))
//关闭文件
fs.closeSync(srcFile)
fs.closeSync(destFile)}
在第二个函数中貌似没有读取到destFile的信息,返回的长度还是数组初始化的长度,并且打印的信息也没有打出来。哪位大佬给解惑一下列。并且存放的文件在哪里找呢
更多关于HarmonyOS鸿蒙Next中使用fs.writeSync貌似没有成功的问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html
无法读取数据也没什么报错吗
更多关于HarmonyOS鸿蒙Next中使用fs.writeSync貌似没有成功的问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
没有啥报错,就是返回的那个readLen的长度是不正常的,
自己回复一下第二个问题,对于destFile的readSync函数,
let readLen1 = fs.readSync(destFile.fd,buf1,{offset : 0,length:"传入要读出来数据的长度"})
这么编写,是可以正常读出来数据了就。确实有点奇怪列,为何那个srcFile调用readSync的时候,没有给length赋值,就能正常读出数据列
在HarmonyOS鸿蒙Next中,fs.writeSync
是用于同步写入文件的方法。如果使用fs.writeSync
没有成功,可能的原因包括文件路径错误、文件权限不足、文件系统问题或代码逻辑错误。确保文件路径正确且应用具有写入权限。检查文件系统是否正常,确保没有其他进程占用文件。确认代码逻辑正确,fs.writeSync
的参数格式符合要求。如果问题依旧,可以尝试使用fs.write
异步方法进行调试,查看是否有更详细的错误信息。
在HarmonyOS鸿蒙Next中使用fs.writeSync
时,如果写入操作未成功,可能的原因包括:
- 文件路径错误:确保文件路径正确且文件存在。
- 权限问题:检查应用是否有写入文件的权限。
- 文件打开模式:确保文件以正确的模式(如
'w'
或'a'
)打开。 - 缓冲区问题:确保传入的缓冲区数据有效且不为空。
- 同步调用问题:
writeSync
是同步操作,确保在调用时没有其他阻塞操作。
建议检查以上几点,并添加错误处理代码以捕获具体错误信息。