鸿蒙:在沙箱目录下压缩或解压文件
1. 前言
压缩文件或解压文件是我们在日常工作中的基本操作,在鸿蒙开发中,我们可以使用zlib接口实现这一能力。
2. 参考文档
https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-file-fshttps://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-file-fs
https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/deflate-and-inflatehttps://developer.huawei.com/consumer/cn/doc/harmonyos-guides/deflate-and-inflate
3. 核心思路
以沙箱目录为基础路径,逐步完成系列文件操作:
- 获取沙箱目录路径作为所有操作的根目录
- 在沙箱根目录创建并写入测试文件(helloWorld.txt)
- 将根目录的测试文件压缩到沙箱的 test01 目录(生成 helloWorld.zip)
- 将 test01 目录的压缩文件解压到沙箱的 test02 目录
- 展示沙箱总目录、test01 和 test02 目录下的文件列表,验证操作结果
4. 核心代码
decompressHelloWorldZipToSandboxTest02Dir() {// 创建目录try {fs.mkdirSync(this.filesDir + "/test02")} catch (err) {console.error('文件夹已存在');}this.decompressFile = this.filesDir + '/test02';let options: zlib.Options = {};zlib.decompressFile(this.outFile, this.decompressFile, options).then((data: void) => {// 检查解压后的文件是否存在(这里假设解压后是data.txt)try {const stat = fs.statSync(this.decompressFile + '/test02/helloWorld.txt');console.info(`解压成功,文件大小: ${stat.size} 字节`);} catch (err) {console.error('解压文件生成失败');}console.info('decompressFile success, data: ' + JSON.stringify(data));}).catch((errData: BusinessError) => {console.error(`decompressFile errCode: ${errData.code}, message: ${errData.message}`);})
}compressHelloWorldTxtToSandboxTest01Dir() {this.inFile = this.filesDir + '/helloWorld.txt';this.outFile = this.filesDir + '/test01/helloWorld.zip';try {// 创建目录fs.mkdirSync(this.filesDir + "/test01")} catch (err) {console.error('文件夹已存在');}// 压缩文件let options: zlib.Options = {};zlib.compressFile(this.inFile, this.outFile, options).then((data: void) => {// 检查压缩文件是否存在try {const stat = fs.statSync(this.outFile);console.info(`压缩成功,文件大小: ${stat.size} 字节`);} catch (err) {console.error('压缩文件生成失败');}console.info('compressFile success, data: ' + JSON.stringify(data));}).catch((errData: BusinessError) => {console.error(`compressFile errCode: ${errData.code}, message: ${errData.message}`);})
}
5. 运行效果
6. 完整代码
Index.ets
import { fileIo as fs, ReadTextOptions } from '@kit.CoreFileKit'
import { BusinessError, zlib } from '@kit.BasicServicesKit'@Entry
@ComponentV2
struct Index {@Local decompressFile: string = ""@Local inFile: string = ""@Local outFile: string = ""@Local filesDir: string = ""context = this.getUIContext().getHostContext()!build() {Column({ space: 100 }) {Row({ space: 10 }) {Text("老羊提示").fontSize(14).fontColor(Color.Gray)Text("请依次点击下方按钮").fontSize(26).fontWeight(FontWeight.Bold)}Column({ space: 20 }) {Text("沙箱目录路径" + this.filesDir)Button("1、获取沙箱路径").onClick(() => {this.getSandboxPath()})Button("2、在沙箱根目录创建 helloWorld.txt 文件").onClick(() => {this.createHelloWorldTxtInSandboxRoot()})Text("文件路径:" + this.inFile)Text("文件要压缩到的路径:" + this.outFile)Button("3、压缩 helloWorld.txt 文件到沙箱 /test01 目录").onClick(() => {this.compressHelloWorldTxtToSandboxTest01Dir()})Text("文件要解压的路径:" + this.decompressFile)Button("4、解压 helloWorld.zip 文件到沙箱 /test02 目录").onClick(() => {this.decompressHelloWorldZipToSandboxTest02Dir()})Button("5、弹窗提示所有的目录下文件列表").onClick(() => {this.showAllDirectoryFilesListInDialog()})}}.width("100%").height("100%").justifyContent(FlexAlign.Center)}showDialog(mes: string) {this.getUIContext().showAlertDialog({ message: mes })}showAllDirectoryFilesListInDialog() {try {const fileList01 = fs.listFileSync(this.filesDir)const fileList02 = fs.listFileSync(this.filesDir + '/test01/')const fileList03 = fs.listFileSync(this.filesDir + '/test02/')const list =["___沙箱总目录___", ...fileList01, "___test01目录___", ...fileList02, "___test02目录___", ...fileList03]this.showDialog(list.join('\n'))} catch (err) {this.showDialog(JSON.stringify(err))}}decompressHelloWorldZipToSandboxTest02Dir() {// 创建目录try {fs.mkdirSync(this.filesDir + "/test02")} catch (err) {console.error('文件夹已存在');}this.decompressFile = this.filesDir + '/test02';let options: zlib.Options = {};zlib.decompressFile(this.outFile, this.decompressFile, options).then((data: void) => {// 检查解压后的文件是否存在(这里假设解压后是data.txt)try {const stat = fs.statSync(this.decompressFile + '/test02/helloWorld.txt');console.info(`解压成功,文件大小: ${stat.size} 字节`);} catch (err) {console.error('解压文件生成失败');}console.info('decompressFile success, data: ' + JSON.stringify(data));}).catch((errData: BusinessError) => {console.error(`decompressFile errCode: ${errData.code}, message: ${errData.message}`);})}compressHelloWorldTxtToSandboxTest01Dir() {this.inFile = this.filesDir + '/helloWorld.txt';this.outFile = this.filesDir + '/test01/helloWorld.zip';try {// 创建目录fs.mkdirSync(this.filesDir + "/test01")} catch (err) {console.error('文件夹已存在');}// 压缩文件let options: zlib.Options = {};zlib.compressFile(this.inFile, this.outFile, options).then((data: void) => {// 检查压缩文件是否存在try {const stat = fs.statSync(this.outFile);console.info(`压缩成功,文件大小: ${stat.size} 字节`);} catch (err) {console.error('压缩文件生成失败');}console.info('compressFile success, data: ' + JSON.stringify(data));}).catch((errData: BusinessError) => {console.error(`compressFile errCode: ${errData.code}, message: ${errData.message}`);})}createHelloWorldTxtInSandboxRoot() {// 创建文件 helloWorld.txtlet inFile = fs.openSync(this.filesDir + '/helloWorld.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);// 写入测试数据for (let index = 0; index < 10; index++) {fs.writeSync(inFile.fd, index + ': hello world, hello world, hello world, hello world, hello world.\n');}// 关闭文件fs.closeSync(inFile);// 读取文本内容let readTextOptions: ReadTextOptions = {offset: 1,length: 0,encoding: 'utf-8'};let stat = fs.statSync(this.filesDir + '/helloWorld.txt');readTextOptions.length = stat.size;let str = fs.readTextSync(this.filesDir + '/helloWorld.txt', readTextOptions);this.showDialog(`文件创建成功\n内容:${str}`)}getSandboxPath() {this.filesDir = this.context.filesDir}
}
觉得有帮助,可以点赞、收藏或关注