HarmonyOS鸿蒙Next中文件复制到指定目录的demo
HarmonyOS鸿蒙Next中文件复制到指定目录的demo 文件复制到指定目录的demo
3 回复
参考
copyFile(fs){
console.log("copyFile!")
let context = getContext(this) as common.UIAbilityContext;
let srcFileDescriptor = context.resourceManager.getRawFdSync('xxx.xx');
//这里填rawfile文件夹下的文件名(包括后缀)
let stat = fs.statSync(srcFileDescriptor.fd)
console.log(`stat isFile:${stat.isFile()}`);
//通过UIAbilityContext获取沙箱地址filesDir,以Stage模型为例
let pathDir = context.filesDir;
console.log("path:",pathDir)
let dstPath = pathDir + "/xxx.xx";
let dest = fs.openSync(dstPath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE)
let bufsize = 4096
let buf = new ArrayBuffer(stat.size)
let off = 0, len = 0, readedLen = 0
while (len = fs.readSync(srcFileDescriptor.fd, buf, { offset: srcFileDescriptor.offset + off, length: bufsize })) {
readedLen += len
fs.writeSync(dest.fd, buf, { offset: off, length: len })
off = off + len
if ((srcFileDescriptor.length - readedLen) < bufsize) {
bufsize = srcFileDescriptor.length - readedLen
}
}
fs.close(dest.fd)
}
更多关于HarmonyOS鸿蒙Next中文件复制到指定目录的demo的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,文件复制到指定目录可以通过ohos.file.fs模块实现。以下是一个简单的demo,展示如何将文件从源路径复制到目标路径:
import fs from '@ohos.file.fs';
async function copyFile(sourcePath: string, destPath: string): Promise<void> {
try {
// 打开源文件
const sourceFile = fs.openSync(sourcePath, fs.OpenMode.READ_ONLY);
// 创建目标文件
const destFile = fs.openSync(destPath, fs.OpenMode.CREATE | fs.OpenMode.WRITE_ONLY);
// 读取源文件内容
const buffer = new ArrayBuffer(1024);
let bytesRead = 0;
while ((bytesRead = fs.readSync(sourceFile.fd, buffer)) > 0) {
// 将内容写入目标文件
fs.writeSync(destFile.fd, buffer, 0, bytesRead);
}
// 关闭文件
fs.closeSync(sourceFile.fd);
fs.closeSync(destFile.fd);
console.log('文件复制成功');
} catch (error) {
console.error('文件复制失败:', error);
}
}
// 示例调用
const sourcePath = '/data/storage/el1/base/files/source.txt';
const destPath = '/data/storage/el1/base/files/destination.txt';
copyFile(sourcePath, destPath);
该demo使用fs.openSync打开源文件和目标文件,通过fs.readSync读取源文件内容,并使用fs.writeSync将内容写入目标文件。最后关闭文件句柄。
在HarmonyOS鸿蒙Next中,可以使用ohos.file.fs模块进行文件操作。以下是一个简单的文件复制到指定目录的示例代码:
import fs from '@ohos.file.fs';
// 源文件路径
let srcPath = '/data/storage/el1/base/files/source.txt';
// 目标目录路径
let destPath = '/data/storage/el1/base/files/destination/';
try {
// 创建目标目录(如果不存在)
fs.mkdirSync(destPath);
// 复制文件
fs.copyFileSync(srcPath, destPath + 'source.txt');
console.log('文件复制成功');
} catch (err) {
console.error('文件复制失败:', err);
}
确保应用有足够的权限访问指定路径。

