当前位置: 首页 > news >正文

鸿蒙:在沙箱目录下压缩或解压文件

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}
}

觉得有帮助,可以点赞、收藏或关注

http://www.dtcms.com/a/481839.html

相关文章:

  • 智能SQL客户端Chat2DB技术解析
  • 电影网站推广什么是网络营销的主要职能之一
  • Transformers库用法示例:解锁预训练模型的强大能力
  • 大气污染扩散calpuff模型:数据预处理、Calmet气象模块、Post Tools 后处理工具及绘图工具
  • 用气安全与能效优化平台
  • 02117 信息组织【第三章】
  • 自己建设淘宝客网站需要备案么wordpress插件 投票
  • Wireshark 4.4.9 设置为中文界面方法
  • 极限AI Coding,腾讯云“黑客松”大赛回顾(内有作品开源)
  • 【工具分享】Dota游戏平台助手
  • 网站制作找云优化口碑好的网站定制公司
  • 精品建站公司2345网址大全下载到桌面
  • HENGSHI SENSE异构过滤架构:基于三层执行引擎的跨源联邦查询性能优化实践
  • 语言模型监督式微调(SFT)概述
  • 又开始了 小程序定制
  • 前端面试-箭头函数
  • 翻译类公司网站模板node做网站后台
  • 2018做网站哪里可以做寄生虫网站
  • 腾讯云的游戏盾怎么样
  • C++函数完全指南:从基础到高级应用
  • 国自然申报·医工交叉热点|单细胞多模态融合破解病理研究痛点
  • html情人节给女朋友做网站WordPress在手机能更新
  • springboot餐厅信息管理系统设计(代码+数据库+LW)
  • Jenkins Share Library教程 —— 高级实战与最佳实践教程
  • Blender图片AI智能一键生成3D模型插件 Pixelmodeller Ai V1.4.9
  • CAA机器学习
  • LeetCode hot100:128 最长连续序列:高效求解
  • 上海网站制作 优化wordpress 去除google
  • [Backstage] 软件模板Scaffolder | 定义“Node.js微服务“
  • 链表操作教学工具