尝试创建一个将资产文件复制到本机应用程序文档文件夹的 Flutter 插件。
对于 iOS,我通过以下代码实现了这一点(见下文)。
但是,由于我对 Android 架构了解不多,所以我想知道我的 Android MethodChannel 代码应该是什么样子。
这个 Flutter 插件的我的 Android 部分需要在 KOTLIN 中!
我需要将文件从 Android 资产文件夹复制到 Android 的 Documents 文件夹——所有这些都在 Flutter 插件和 Kotlin 中完成!
同样,我已经准备好了 Swift 中的 iOS。缺少的是 Kotlin 中的 Android 对应部分。你对此有什么帮助吗?
.
这是 Swift 中 iOS FlutterMethodChannel 的工作代码:
(即,它将文件从主捆绑包复制到 iPhone 的 Documents-Directory...)
import UIKit
private func copyFile(fileName: String) -> String {
let fileManager = FileManager.default
let documentsUrl = fileManager.urls(for: .documentDirectory,
in: .userDomainMask)
guard documentsUrl.count != 0 else {
return "Could not find documents URL"
}
let finalURL = documentsUrl.first!.appendingPathComponent(fileName)
if !( (try? finalURL.checkResourceIsReachable()) ?? false) {
let documentsURL = Bundle.main.resourceURL?.appendingPathComponent(fileName)
do {
try fileManager.copyItem(atPath: (documentsURL?.path)!, toPath: finalURL.path)
return "\(finalURL.path)"
} catch let error as NSError {
return "Couldn't copy file to final location! Error:\(error.description)"
}
} else {
return "\(finalURL.path)"
}
}
在 Kotlin 中,我尝试过这个 - 但它根本不起作用...... :(
import java.io.File
private fun copyFileTrial1(fileName: String): String {
File src = new File("../../assets/${fileName}");
File dst = new File("../../DocumentsFolder/${fileName}", src.getName());
FileInputStream inStream = new FileInputStream(src);
FileOutputStream outStream = new FileOutputStream(dst);
FileChannel inChannel = inStream.getChannel();
FileChannel outChannel = outStream.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
inStream.close();
outStream.close();
return "hello1"
}
或者我试过这个 - 但又一次 - 完全没有成功:(
private fun copyFileTrial2(fileName: String): String {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(fileName);
String outDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/X/Y/Z/" ;
File outFile = new File(outDir, filenfileNameame);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + fileName, e);
}
return "hello2"
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}