4、文件操作
说明:
> 调用安卓底层,获取文件列表、路径是否文件夹、文件是否存在、删除文件、读取文件内容、写入文件、获取文件(夹)大小、压缩、解压。
---
获取文件列表:
```
// 不传参获取的是手机根目录文件列表:
var fileList = wc.getFileList();
// 获取“WebCat”目录下文件列表,可根据实际传入文件夹名或路径
var fileList = wc.getFileList("WebCat");
console.log(fileList);
```
返回示例:
```
// name: 文件(夹)名称
// type: dir(文件夹)、file(文件)
// size: 如果是文件夹,返回文件夹内文件数量;如果是文件,返回文件大小(单位:byte)
[{
"name": "cache",
"size": "3",
"type": "dir"
},{
"name": "project",
"size": "3",
"type": "dir"
},{
"name": "1.txt",
"size": "463",
"type": "file"
}]
```
---
路径是否文件夹:
```
// 根据实际情况传入路径
var path = "WebCat/project";
var isDir = wc.isDir(path);
if(isDir) {
wc.alert("是文件夹");
} else {
wc.alert("不是文件夹");
}
```
---
文件是否存在:
```
// 根据实际情况传入文件路径
var filePath = "WebCat/project/demo/index.html";
var fileExist= wc.fileExist(filePath);
if(fileExist) {
wc.alert("存在");
} else {
wc.alert("不存在");
}
```
---
删除文件:
```
// 根据实际情况传入文件路径
var filePath = "WebCat/project/demo/index.html";
var boo = wc.delFile(filePath);
if(boo) {
wc.alert("删除成功");
} else {
wc.alert("删除失败");
}
```
---
读取文件内容:
```
// 根据实际情况传入文件路径
var filePath = "WebCat/project/demo/index.html";
var str = wc.read(filePath);
wc.alert(str);
```
---
写入文件:
```
// 需要写入到的文件路径
var filePath = "WebCat/1.txt";
// 需要写入的内容
var str = "Hello world!";
wc.write(filePath, str);
```
---
获取文件大小:
```
// 根据实际情况传入文件路径
var filePath = "WebCat/project/demo/index.html";
// 单位:byte
var size = wc.getFileSize(filePath);
wc.alert(size);
```
---
压缩文件目录:
```
// 根据实际情况传入文件路径
// 将"WebCat/project"目录压缩到"WebCat/project.zip"
var path = "WebCat/project";
var targetPath = "WebCat/project.zip";
var boo = wc.zip(path, targetPath);
if(boo) {
wc.alert("压缩成功");
} else {
wc.alert("压缩失败");
}
```
---
解压文件:
```
// 根据实际情况传入文件路径
// 将"WebCat/project.zip"文件解压到"WebCat/project"目录
var path = "WebCat/project.zip";
var targetPath = "WebCat/project";
var boo = wc.unzip(path, targetPath);
if(boo) {
wc.alert("解压成功");
} else {
wc.alert("解压失败");
}
```