androidFileCopy.js
2.82 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
* targetSdk>=29 时 plus.io 无法以绝对路径读写 /data/data、/data/user;
* 本应用沙箱内可用 Java File 复制(与 DCloud 文档说明一致)。
*/
function normalizeAbs(path) {
if (!path) return ''
return String(path)
.replace(/^file:\/\//, '')
.trim()
}
export function isInternalSandboxAbsPath(path) {
const p = normalizeAbs(path)
return p.startsWith('/data/data/') || p.startsWith('/data/user/')
}
export function resolvePlusAbsolutePath(relativeOrUrl) {
if (!relativeOrUrl || typeof plus === 'undefined') return ''
try {
return normalizeAbs(plus.io.convertLocalFileSystemURL(relativeOrUrl))
} catch (_) {
return normalizeAbs(relativeOrUrl)
}
}
export function fileExistsByAndroid(absPath) {
const p = normalizeAbs(absPath)
if (!p || typeof plus === 'undefined') return false
try {
const File = plus.android.importClass('java.io.File')
const f = plus.android.newObject('java.io.File', p)
return !!f.exists() && f.isFile()
} catch (_) {
return false
}
}
export function copyFileByAndroid(srcAbs, destAbs) {
const srcPath = normalizeAbs(srcAbs)
const destPath = normalizeAbs(destAbs)
if (!srcPath || !destPath) {
return Promise.reject(new Error('copyFileByAndroid: 路径为空'))
}
return new Promise((resolve, reject) => {
try {
const File = plus.android.importClass('java.io.File')
const FileInputStream = plus.android.importClass('java.io.FileInputStream')
const FileOutputStream = plus.android.importClass('java.io.FileOutputStream')
const srcFile = plus.android.newObject('java.io.File', srcPath)
if (!srcFile.exists()) {
reject(new Error(`源文件不存在:${srcPath}`))
return
}
const destFile = plus.android.newObject('java.io.File', destPath)
const parent = destFile.getParentFile()
if (parent && !parent.exists() && !parent.mkdirs()) {
reject(new Error(`无法创建目标目录:${parent.getAbsolutePath()}`))
return
}
const inputStream = plus.android.newObject('java.io.FileInputStream', srcFile)
const outputStream = plus.android.newObject('java.io.FileOutputStream', destFile)
const buffer = plus.android.newObject('byte[]', 8192)
let length = plus.android.invoke(inputStream, 'read', buffer)
while (length > 0) {
plus.android.invoke(outputStream, 'write', buffer, 0, length)
length = plus.android.invoke(inputStream, 'read', buffer)
}
plus.android.invoke(outputStream, 'flush')
plus.android.invoke(inputStream, 'close')
plus.android.invoke(outputStream, 'close')
if (!destFile.exists()) {
reject(new Error(`复制后目标不存在:${destPath}`))
return
}
resolve(destPath)
} catch (e) {
reject(new Error(e?.message || String(e)))
}
})
}