ITeye博客

android中加载assets中的资源文件

sfshine · 2012-11-17 11:20 · Android · 移动开发 · Markdown

1.直接读取inputstream流

 

[java] view plaincopyprint?

  1. AssetManager assetManager = getAssets();//獲取其輸入流 然後直接讀取這個流
  2. InputStream inputStream = assetManager.open("1.txt");

 

 

2.複製asset指定文件到制定地方

 

[java] view plaincopyprint?

  1. /**
  2. * Copy assets util
  3. * @param path The dictionary path
  4. * @param filename  The filename
  5. * @param context  Your context
  6. */
  7. public void copyAssets(String path, String filename,Context context) {
  8. try {
  9. File fpath = new File(PATH);
  10. if (!fpath.isDirectory()) {
  11. fpath.mkdirs();
  12. }
  13. AssetManager assetManager = context.getAssets();
  14. InputStream inputStream = assetManager.open(filename);
  15. FileOutputStream fileOutputStream = new FileOutputStream(PATH
  16. + filename);
  17. byte[] buffer = new byte[1024];
  18. int read;
  19. while ((read = inputStream.read(buffer)) != -1) {
  20. fileOutputStream.write(buffer, 0, read);
  21. }
  22. inputStream.close();
  23. inputStream = null;
  24. fileOutputStream.flush();
  25. fileOutputStream.close();
  26. fileOutputStream = null;
  27. } catch (Exception e) {
  28. // TODO: handle exception
  29. }
  30. }

3.複製assets下所有文件到指定地方

 

 

[java] view plaincopyprint?

  1. private static void copyAssets(Context context) {//copy Assets的方法
  2. AssetManager assetManager = context.getAssets();
  3. String[] files = null;
  4. try {
  5. files = assetManager.list("");
  6. } catch (IOException e) {
  7. }
  8. for (int i = 0; i < files.length; i++) {
  9. InputStream in = null;
  10. OutputStream out = null;
  11. try {
  12. if (!(new File(Tips.DATA_PATH + files[i])).exists()) {
  13. in = assetManager.open(files[i]);
  14. out = new FileOutputStream(Tips.DATA_PATH + files[i]);
  15. Tips.copyFile(in, out);
  16. in.close();
  17. in = null;
  18. out.flush();
  19. out.close();
  20. out = null;
  21. }
  22. } catch (Exception e) {
  23. }
  24. }
  25. }
  26. public static void copyFile(InputStream in, OutputStream out)
  27. throws IOException {
  28. byte[] buffer = new byte[1024];//做了个缓冲流
  29. int read;
  30. while ((read = in.read(buffer)) != -1) {
  31. out.write(buffer, 0, read);
  32. }
  33. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。