2

アセット ファイルをネイティブのアプリケーション ドキュメント フォルダーにコピーする Flutter プラグインを作成しようとしています。

iOS の場合、次のコードでこれを実現しました (以下を参照)。

しかし、私は Android アーキテクチャについてあまり知識がないので、Android MethodChannel コードがどのように見えるべきかを知りたいと思っています。

この Flutter プラグインの Android 部分は KOTLIN にする必要があります。

Android のアセット フォルダーから Android のドキュメント フォルダーへのファイル コピーが必要です。これはすべて Flutter プラグインと Kotlin で行われます。

繰り返しますが、Swift の iOS が用意されています。欠けているのは、Android in Kotlin の対応部分です。これについて何か助けはありますか?

.

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);
    }
}
4

1 に答える 1