HarmonyOS 鸿蒙Next:对视频文件分段读取然后分段写入另一个文件
HarmonyOS 鸿蒙Next:对视频文件分段读取然后分段写入另一个文件
是将一个视频文件分段读取后上传到服务器,我测试直接读取整个视频文件上传到服务器是ok的,但是分段有个offset参数,为了验证这个分段的问题,我将读取的分段数据,写入另一个test.mp4文件,发现无法播放,现在是这样的: let blockLength = 1024 * 500 let position = 0 let mBlock = getBlock(position, fileSize, filePath, blockLength) export function copyFile(position: number, fileSize: number, mBlock: ArrayBuffer, blockLength: number) { let filePath = FileUtil.getCacheDirPath() + “/test.mp4”; let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); fs.write(file.fd, mBlock, {offset: position}).then((writeLen: number) => { console.info(“write data to file succeed and size is:” + writeLen); position+= mBlock.byteLength mBlock = getBlock(position, fileSize, filePath, blockLength) if (mBlock.byteLength > 0) { copyFile(position, fileSize, mBlock, blockLength) } }).catch((err: BusinessError) => { console.error("write data to file failed with error message: " + err.message + ", error code: " + err.code); }).finally(() => { fs.closeSync(file); }); } function getBlock(position: number, totalSize: number, videoFilename: string, blockSize: number): ArrayBuffer { let result: ArrayBuffer = new ArrayBuffer(Math.min(totalSize-position, blockSize)) let file = fs.openSync(videoFilename, fs.OpenMode.READ_ONLY) fs.readSync(file.fd, result, {offset: position}) fs.closeSync(file) return result } 我尝试offset+1也不行,想知道这个分段读取和写入要对offset做什么处理?
2 回复
以下是分段读取的代码:
let fd: number = fileIo.openSync(this.selectFilePath, 0o0).fd;
const file = fs.openSync(this.selectFilePath, fs.OpenMode.READ_ONLY);
let videoSize = fs.statSync(file.fd).size;
let arrayBuffer = new ArrayBuffer(videoSize);
fs.read(file.fd, arrayBuffer, (err: BusinessError, readLen: number) => {
if (err) {
console.error("read failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("read file data succeed");
let buf = buffer.from(arrayBuffer, 0, readLen);
console.info(`The content of file: ${buf.toString()}`);
}
fs.closeSync(file);
});
fs.closeSync(file);
在HarmonyOS鸿蒙Next系统中,对于视频文件的分段读取与写入操作,可以通过Java或Kotlin等编程语言结合文件I/O流来实现。以下是一个基于Java的简要实现思路:
-
打开源文件:使用
FileInputStream
打开需要读取的视频文件。 -
分段读取:通过循环和
FileInputStream.read(byte[] b, int off, int len)
方法,将视频文件按指定大小(如1MB)分段读取到字节数组中。 -
写入目标文件:使用
FileOutputStream
打开或创建目标文件,并通过FileOutputStream.write(byte[] b, int off, int len)
方法,将分段读取的数据写入目标文件。 -
关闭流:完成所有分段操作后,确保关闭所有打开的流,以释放资源。
示例代码框架(省略了具体异常处理和资源管理细节):
FileInputStream fis = new FileInputStream("源文件路径");
FileOutputStream fos = new FileOutputStream("目标文件路径");
byte[] buffer = new byte[1024 * 1024]; // 1MB缓冲区
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
fis.close();
fos.close();
注意:实际操作中需考虑异常处理、资源管理(如使用try-with-resources语句)及文件权限等问题。如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html