文件分类
按所有者:
-
应用文件:所有者为应用,包括应用安装文件、应用资源文件、应用缓存文件等。
-
用户文件:所有者是登录到该终端设备的用户,包括用户私有的图片、视频、音频、文档等。
-
系统文件:与应用和用户无关的其他文件,包括公共库、设备文件、系统资源文件等。
应用沙箱(虚拟目录,仅应用自己可见)
应用文件路径详细
写文件
//WriteFile.ets
import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';let context = getContext(this) as common.UIAbilityContext
let filesDir = context.filesDir;/*** 写文件* 把内容写入一个文件* @param content 内容字符串*/
export function writeFile(content: string): void {let filePath = filesDir + '/test.txt' //文件路径// 用文件路径,创建一个文件流。w+: 覆盖式读写,无论该文件存在与否let fileStream = fileIo.createStreamSync(filePath, "w+");fileStream.writeSync(content);fileStream.close();
}
读文件
//ReadFile.ets
import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { buffer } from '@kit.ArkTS';// 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
let res: string = '';export function readFile(): string {//文件路径let filePath = filesDir + '/test.txt'//获取文件状态let stat = fileIo.statSync(filePath)let size = stat.size //文件大小//设置一个读取缓冲区,大小与文件大小一致let buf = new ArrayBuffer(size)// 根据文件路径打开文件流let fileStream = fileIo.createStreamSync(filePath, "r+")// 读取信息到缓冲区,同步方法(sync)fileStream.readSync(buf)// 文件读取到缓冲区后,再转换为通用buffer类型(二进制)let con = buffer.from(buf, 0)//buffer二进制数据,转换为字符串类型res = con.toString()//关闭文件流fileStream.close()return res;
}
文件分享
应用场景:应用A主动分享文件给应用B,应用B完成文件接收。
- URI分享: 把文件在沙箱中的路径,转换成实际的物理路径(URI),即可分享。
文件分享: systemShare
//ShareFile.ets
import { Want, wantConstant } from '@kit.AbilityKit';
import { common } from '@kit.AbilityKit';
import { fileUri } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { promptAction } from '@kit.ArkUI';
import { uniformTypeDescriptor } from '@kit.ArkData';
import { systemShare } from '@kit.ShareKit';let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;export
function shareFile2(){// 获取文件的沙箱路径let filePath = filesDir + '/test.txt'// 将沙箱路径转换为urilet uri1 = fileUri.getUriFromPath(filePath)let utd1 = ''if (canIUse('SystemCapability.DistributedDataManager.UDMF.Core')) {utd1 = uniformTypeDescriptor.UniformDataType.PLAIN_TEXT}let data = new systemShare.SharedData({utd: utd1,uri: uri1})let ctrl = new systemShare.ShareController(data)ctrl.show(context,{// 选用一种预览previewMode: systemShare.SharePreviewMode.DETAIL,// 选用一种选择模式, 例如单选selectionMode: systemShare.SelectionMode.SINGLE})
}export default
function shareFile(){// 获取文件的沙箱路径let filePath = filesDir + '/test.txt'// 将沙箱路径转换为urilet uri = fileUri.getUriFromPath(filePath)let want: Want = {// 配置被分享文件的读写权限,例如对被分享应用进行读写授权flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION |wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION,// 配置分享应用的隐式拉起规则action: 'ohos.want.action.sendData',uri: uri,type: 'text/plain'}context.startAbility(want).then(() => {promptAction.showToast({message: '分享成功'})}).catch((err: BusinessError) => {promptAction.showToast({message: `分享失败:${err.code}, 原因:${err.message}`,duration: 5000})});
}
文件选择器 - Picker
- PhotoViewPicker:图片/视频
- DocumentViewPicker:各式文件
- AudioViewPicker:音频
import { picker } from '@kit.CoreFileKit';
let photoPicker = new picker.PhotoViewPicker()
let docPicker = new picker.DocumentViewPicker()
let audioPicker = new picker.AudioViewPicker()
import fileIo from "@ohos:file.fs";
import picker from "@ohos:file.picker";
import type common from "@ohos:app.ability.common";
let context = getContext(this) as common.UIAbilityContext;
export async function photoPickerGetUri(): Promise<string> {//picker的选项配置let PhotoSelectOptions = new picker.PhotoSelectOptions();PhotoSelectOptions.maxSelectNumber = 1; //最大可选数let photoPicker = new picker.PhotoViewPicker();try {let result = await photoPicker.select(PhotoSelectOptions);console.info('选择结果 uri: ' + JSON.stringify(result));let photosUris = result.photoUris;return Promise.resolve(photosUris[0].toString());}catch (e) {console.error('出错: ' + JSON.stringify(e));}return Promise.reject();
}
export async function photoSave() {let options = new picker.PhotoSaveOptions;options.newFileNames = ['1.jpg']; //保存文件名let picker1 = new picker.PhotoViewPicker();try {let result = await picker1.save(options);let file = await fileIo.open(result[0], fileIo.OpenMode.READ_WRITE);let buffer = context.resourceManager.getMediaContentSync({ "id": 16777238, "type": 20000, params: [], "bundleName": "com.example.filesmanger", "moduleName": "entry" }.id);await fileIo.write(file.fd, buffer.buffer);}catch (e) {console.error('保存失败:' + JSON.stringify(e));}
}
Picker保存文件
import { picker, fileIo } from '@kit.CoreFileKit';
import { buffer } from '@kit.ArkTS';export async function saveToUser(content: string) {try {let options = new picker.DocumentSaveOptions()options.newFileNames = ['test123.txt']let picker1 = new picker.DocumentViewPicker()let result = await picker1.save(options)//打开文件,读写模式let file = fileIo.openSync(result[0], fileIo.OpenMode.READ_WRITE)fileIo.writeSync(file.fd, content) //写入内容console.info('保存成功, uri: ' + JSON.stringify(result))} catch (error) {console.error('保存错误:' + JSON.stringify(error));}
}export async function readUserFile(): Promise<string> {try {let options = new picker.DocumentSelectOptions()let documentPicker = new picker.DocumentViewPicker()let result = await documentPicker.select(options)let file = fileIo.openSync(result[0], fileIo.OpenMode.READ_WRITE)let buf = new ArrayBuffer(fileIo.statSync(file.fd).size)fileIo.readSync(file.fd, buf)let con = buffer.from(buf, 0)return Promise.resolve(con.toString())} catch (err) {console.error('读取失败: ' + JSON.stringify(err));}return Promise.reject()
}