FileUtils.ets
1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import fs from '@ohos.file.fs';
import { BusinessError } from '@kit.BasicServicesKit';
import { util } from '@kit.ArkTS';
export class FileUtils {
// 文件是否存在,忽略错误
static fileExsit(path: string) : Promise<boolean> {
return new Promise((reslove, fail) => {
fs.stat(path).then(() => {
reslove(true)
}).catch((error: BusinessError) => {
if (error.code = 13900002) {
reslove(false)
} else {
reslove(true)
}
})
});
}
static makeDirIfNotExsit(path: string) : Promise<void> {
return new Promise((reslove, fail) => {
fs.stat(path).then(() => {
reslove()
}).catch((error: BusinessError) => {
if (error.code = 13900002) {
fs.mkdirSync(path)
}
reslove()
})
})
}
static readFile(path: string): ArrayBuffer {
try {
let stat = fs.statSync(path)
let fd = fs.openSync(path, fs.OpenMode.READ_ONLY).fd;
let length = stat.size
let buf = new ArrayBuffer(length);
fs.readSync(fd, buf)
fs.closeSync(fd)
return buf
} catch (e) {
console.log("FileUtils - readFilePicSync " + e)
return new ArrayBuffer(0)
}
}
static readFileAsString(path: string): string {
const data = FileUtils.readFile(path)
let decoder = util.TextDecoder.create('utf-8');
let str = decoder.decodeToString(new Uint8Array(data));
return str
}
}