Android 는 Assets 파일 을 SD 카드 로 복사 합 니 다.

5077 단어 AndroidAssetsSD
에 셋 파일 소개
assets 폴 더 안의 파일 은 모두 원본 파일 형식 을 유지 하고 있 으 며,AssetManager 로 바이트 흐름 으로 파일 을 읽 어야 합 니 다.
1.먼저 Activity 에서 getAssets()를 호출 하여 AssetManager 인용 을 가 져 옵 니 다.
2.AssetManager 의 open(String fileName,int accessMode)방법 으로 읽 을 파일 과 접근 모드 를 지정 하면 입력 스 트림 을 얻 을 수 있 습 니 다.
3.그 다음 에 open file 이 있 는 input Stream 으로 파일 을 읽 고 읽 은 후에 input Stream.close()를 기억 합 니 다.
4.AssetManager.close()를 호출 하여 AssetManager 를 닫 습 니 다.
패키지 클래스
코드 는 단일 모드 를 따 릅 니 다.예 를 들 어:

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * Created by shenhua on 1/17/2017.
 * Email [email protected]
 */
public class FileUtils {

 private static FileUtils instance;
 private static final int SUCCESS = 1;
 private static final int FAILED = 0;
 private Context context;
 private FileOperateCallback callback;
 private volatile boolean isSuccess;
 private String errorStr;

 public static FileUtils getInstance(Context context) {
  if (instance == null)
   instance = new FileUtils(context);
  return instance;
 }

 private FileUtils(Context context) {
  this.context = context;
 }

 private Handler handler = new Handler(Looper.getMainLooper()) {
  @Override
  public void handleMessage(Message msg) {
   super.handleMessage(msg);
   if (callback != null) {
    if (msg.what == SUCCESS) {
     callback.onSuccess();
    }
    if (msg.what == FAILED) {
     callback.onFailed(msg.obj.toString());
    }
   }
  }
 };

 public FileUtils copyAssetsToSD(final String srcPath, final String sdPath) {
  new Thread(new Runnable() {
   @Override
   public void run() {
    copyAssetsToDst(context, srcPath, sdPath);
    if (isSuccess)
     handler.obtainMessage(SUCCESS).sendToTarget();
    else
     handler.obtainMessage(FAILED, errorStr).sendToTarget();
   }
  }).start();
  return this;
 }

 public void setFileOperateCallback(FileOperateCallback callback) {
  this.callback = callback;
 }

 private void copyAssetsToDst(Context context, String srcPath, String dstPath) {
  try {
   String fileNames[] = context.getAssets().list(srcPath);
   if (fileNames.length > 0) {
    File file = new File(Environment.getExternalStorageDirectory(), dstPath);
    if (!file.exists()) file.mkdirs();
    for (String fileName : fileNames) {
     if (!srcPath.equals("")) { // assets        
      copyAssetsToDst(context, srcPath + File.separator + fileName, dstPath + File.separator + fileName);
     } else { // assets    
      copyAssetsToDst(context, fileName, dstPath + File.separator + fileName);
     }
    }
   } else {
    File outFile = new File(Environment.getExternalStorageDirectory(), dstPath);
    InputStream is = context.getAssets().open(srcPath);
    FileOutputStream fos = new FileOutputStream(outFile);
    byte[] buffer = new byte[1024];
    int byteCount;
    while ((byteCount = is.read(buffer)) != -1) {
     fos.write(buffer, 0, byteCount);
    }
    fos.flush();
    is.close();
    fos.close();
   }
   isSuccess = true;
  } catch (Exception e) {
   e.printStackTrace();
   errorStr = e.getMessage();
   isSuccess = false;
  }
 }

 public interface FileOperateCallback {
  void onSuccess();

  void onFailed(String error);
 }

}
호출 코드
그림 과 같은 apks 의 파일 을 SD 카드 의 app/apks 디 렉 터 리 에 복사 하려 면 이렇게 호출 합 니 다.

FileUtils.getInstance(Context context).copyAssetsToSD("apks","app/apks");
\#\##파일 복사 가 완료 되 었 을 때의 리 셋 을 받 으 려 면 다음 코드 를 사용 하 십시오.

FileUtils.getInstance(Context context).copyAssetsToSD("apks","app/apks").setFileOperateCallback(new FileUtils.FileOperateCallback() {
 @Override
  public void onSuccess() {
  // TODO:        ,     
   }

   @Override
   public void onFailed(String error) {
    // TODO:        ,     
   }
  });
코드 설명
위의 코드 에서 하나의 context 모드 를 통 해 FileUtils 인 스 턴 스 를 얻 고 인 스 턴 스 를 통 해 copy AssetsToSD()방법,방법 적 인 파 라 메 터 를 호출 합 니 다.
  • String srcPath 는 assets 폴 더 의 한 폴 더 이름 에 전 달 됩 니 다.상기 apks 와 같이 빈'문자'를 SD 로 복사 한 후 assets 폴 더 의 모든 파일 을 기본적으로 복사 합 니 다
  • 4
  • String sdPath 는 파일 을 복사 하고 자 하 는 위치 로 전 송 됩 니 다.예 를 들 어 SD 카드 의"abc"폴 더 는"abc"로 전 송 됩 니 다
  • 이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

    좋은 웹페이지 즐겨찾기