1.創(chuàng)建文件
createFile(fileName: string, content: string): string {
// 獲取應(yīng)用文件路徑
let context = getContext(this) as common.UIAbilityContext;
let filesDirPath = context.filesDir + '/' + fileName;
// 新建并打開(kāi)文件
let file = fs.openSync(filesDirPath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
// 寫(xiě)入一段內(nèi)容至文件
let writeLen = fs.writeSync(file.fd, content);
// 從文件讀取一段內(nèi)容
let buf = new ArrayBuffer(1024);
let readLen = fs.readSync(file.fd, buf, { offset: 0 });
// 關(guān)閉文件
fs.closeSync(file);
return filesDirPath
}
2.將沙箱文件移動(dòng)到分布式文件夾
/**
* 創(chuàng)建分布式文件
*/
async createDistributedFile(uri: string) {
// 獲取應(yīng)用文件路徑
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.distributedFilesDir;
let fileName = this.getFileName(uri)
try {
let destUriPath = filesDir + '/' + fileName
this.tempFilePath = fileName
//給新建的文件寫(xiě)入內(nèi)容
// mMediaFileUtils.writeFileContent(destUriPath,content)
// 新建并打開(kāi)文件
let writeFile = fs.openSync(destUriPath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
//設(shè)置文件權(quán)限
securityLabel.setSecurityLabel(destUriPath, 's1').then(() => {
})
// fs.write(file.fd,content)
//讀取原文件內(nèi)容
// 讀取圖片為buffer
const file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
let photoSize = fs.statSync(file.fd).size;
let buffer = new ArrayBuffer(photoSize);
fs.readSync(file.fd, buffer);
fs.closeSync(file);
//開(kāi)始寫(xiě)入內(nèi)容
let writeLen = fs.write(writeFile.fd, buffer)
} catch (error) {
}
}
3.讀取分布式文件
/**
* 讀取分布式文件
* @param filePath
*/
readDistributedFile(filePath: string) {
let context = getContext(this) as common.UIAbilityContext;
let distributedFilesDir = context.distributedFilesDir;
let distributedFilesDirs = fs.listFileSync(distributedFilesDir);
for (let i = 0; i < distributedFilesDirs.length; i++) {
let fileName = distributedFilesDir + '/' + distributedFilesDirs[i]
this.readFile(fileName)
}
}
4.讀取文件內(nèi)容
/**
* 讀取文件
* @param filePath 文件路徑
*/
readFile(filePath: string) {
try {
// 打開(kāi)分布式目錄下的文件
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE);
// 定義接收讀取數(shù)據(jù)的緩存
let arrayBuffer = new ArrayBuffer(4096);
// 讀取文件的內(nèi)容庄拇,返回值是讀取到的字節(jié)個(gè)數(shù)
class Option {
public offset: number = 0;
public length: number = 0;
}
let option = new Option();
option.length = arrayBuffer.byteLength;
let num = fs.readSync(file.fd, arrayBuffer, option);
// 打印讀取到的文件數(shù)據(jù)
let buf = buffer.from(arrayBuffer, 0, num);
Log.info('讀取的文件內(nèi)容: ' + buf.toString());
} catch (error) {
let err: BusinessError = error as BusinessError;
Log.error(`Failed to openSync / readSync. Code: ${err.code}, message: ${err.message}`);
}
}
5.產(chǎn)看文件列表(沙箱和分布式文件夾)
/**
* 查看文件列表 沙箱文件夾 和 分布式文件夾
*/
lookFilesList(): string {
//沙箱文件夾
let allFiles = ''
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
let files = fs.listFileSync(filesDir);
for (let i = 0; i < files.length; i++) {
Log.info(`當(dāng)前設(shè)備文件 name: ${files[i]}`);
}
//分布式文件夾
let distributedFilesDir = context.distributedFilesDir;
Log.info('context.distributedFilesDir: ' + distributedFilesDir)
let distributedFilesDirs = fs.listFileSync(distributedFilesDir);
if (distributedFilesDirs.length > 0) {
for (let i = 0; i < distributedFilesDirs.length; i++) {
Log.info(`分布式文件 name: ${distributedFilesDirs[i]}`);
}
}
return allFiles;
}
6.刪除分布式下指定文件
/**
* 刪除分布式指定文件
*/
deleteDistributedFile(fileName: string) {
let context = getContext(this) as common.UIAbilityContext;
let filePath = context.distributedFilesDir + '/' + fileName
securityLabel.setSecurityLabel(filePath, 's1').then(() => {
Log.info('Succeeded in setSecurityLabeling.');
})
try {
fs.rmdir(filePath)
Log.info('刪除文件成功')
} catch (error) {
let err: BusinessError = error as BusinessError;
Log.error(`Failed to openSync / readSync. Code: ${err.code}, message: ${err.message}`);
}
}
7. 刪除本地文件
/**
* 刪除本地文件
*/
deleteCurrentDeviceFile() {
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
let filesDirs = fs.listFileSync(filesDir);
if (filesDirs.length <= 0) {
return
}
let fileName = filesDirs + '/' + filesDirs[0]
securityLabel.setSecurityLabel(fileName, 's1').then(() => {
Log.info('Succeeded in setSecurityLabeling.');
})
try {
fs.rmdir(fileName)
Log.info('刪除文件成功')
} catch (error) {
let err: BusinessError = error as BusinessError;
Log.error(`Failed to openSync / readSync. Code: ${err.code}, message: ${err.message}`);
}
}
8.獲取文件名
/**
* 獲取文件名
* @param filePath
* @returns
*/
getFileName(filePath: string): string {
const parts = filePath.split('/');
if (parts.length === 0) {
return '';
} // 如果沒(méi)有找到任何斜杠注服,返回null
const fileNameWithExtension = parts[parts.length - 1];
const fileNameParts = fileNameWithExtension.split('.');
if (fileNameParts.length < 2) {
return fileNameWithExtension;
} // 如果沒(méi)有擴(kuò)展名,直接返回文件名
// return fileNameParts[0]; // 返回文件名(不含擴(kuò)展名)
return fileNameWithExtension; // 返回文件名,含擴(kuò)展名
}
9.保存文件到本地文件夾
/**
* 拉起picker保存文件
*/
async saveFile(fileName: string):Promise<string>{
let saveFileUri = ''
try {
let DocumentSaveOptions = new picker.DocumentSaveOptions();
DocumentSaveOptions.newFileNames = [fileName];
let documentPicker = new picker.DocumentViewPicker();
await documentPicker.save(DocumentSaveOptions).then( (DocumentSaveResult) => {
if (DocumentSaveResult !== null && DocumentSaveResult !== undefined) {
let uri = DocumentSaveResult[0] as string;
this.realFileUri = uri
this.realSaveFile(fileName)
saveFileUri = uri
}
}).catch((err: BusinessError) => {
Log.error('saveFile-DocumentViewPicker.save failed with err: ' + JSON.stringify(err));
});
} catch (err) {
Log.error('saveFile-DocumentViewPicker failed with err: ' + err);
}
return saveFileUri
}
realFileUri: string = ''
/**
* 真正開(kāi)始保存文件
*/
async realSaveFile(fileName: string) {
let context = getContext(this) as common.UIAbilityContext;
let pathDir = context.distributedFilesDir;
// 獲取分布式目錄的文件路徑
let filePath = pathDir + '/' + fileName;
// 讀取buffer
const file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
let photoSize = fs.statSync(file.fd).size;
let buffer = new ArrayBuffer(photoSize);
fs.readSync(file.fd, buffer);
fs.closeSync(file);
let saveFile = fs.openSync(this.realFileUri, fs.OpenMode.WRITE_ONLY);
let writeLen = fs.write(saveFile.fd, buffer)
Log.info(`save file uri success ~~~~~` + writeLen);
//保存成功以后刪除分布式上面的文件
this.deleteDistributedFile(filePath)
}