Android 中資源分為兩種,一種是res下可編譯的資源文件, 這種資源文件系統會在R.Java里面自動生成該資源文件的ID,訪問也很簡單,只需要調用R.XXX.id即可;第二種就是放在assets文件夾下面的原生資源文件,放在這個文件夾下面的文件不會被R文件編譯,所以不能像第一種那樣直接使用.Android提供了一個工具類,方便我們操作獲取assets文件下的文件:AssetManager
介紹函數
String[] list(String path);//列出該目錄下的下級文件和文件夾名稱
InputStream open(String fileName);//以順序讀取模式打開文件,默認模式為ACCESS_STREAMING
InputStream open(String fileName, int accessMode);//以指定模式打開文件。讀取模式有以下幾種:
//ACCESS_UNKNOWN : 未指定具體的讀取模式
//ACCESS_RANDOM : 隨機讀取
//ACCESS_STREAMING : 順序讀取
//ACCESS_BUFFER : 緩存讀取
void close()//關閉AssetManager實例
加載assets目錄下的網頁
webView.loadUrl("file:///android_asset/html/index.htmll");
說明:這種方式可以加載assets目錄下的網頁,並且與網頁有關的css,js,圖片等文件也會的加載。
加載assets目錄下的圖片資源
InputStream is = getAssets().open(fileName);
bitmap = BitmapFactory.decodeStream(is);
ivImg.setImageBitmap(bitmap);
加載assets目錄下文本文件
InputStream is = getAssets().open(fileName);
int lenght = is.available();
byte[] buffer = new byte[lenght];
is.read(buffer);
String result = = new String(buffer, "utf8");
加載assets目錄下音樂
// 打開指定音樂文件,獲取assets目錄下指定文件的AssetFileDescriptor對象
AssetFileDescriptor afd = am.openFd(music);
mPlayer.reset();
// 使用MediaPlayer加載指定的聲音文件。
mPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
// 准備聲音
mPlayer.prepare();
// 播放
mPlayer.start();
加載assets目錄下視頻
private void initview() {
vv = (CustomVideoView) view.findViewById(R.id.videoView111);
//vv.setVideoPath("/mnt/hd/Wonder Girls - Nobody.avi");
Uri uri = copyFile("one.3gp");
vv.setVideoURI(uri);
vv.start();
}
public Uri copyFile(String name) {
try {
File dir = getActivity().getFilesDir();
File file = new File(dir, name);
if (file.exists()) {
Log.d("Test", "=========file exist=========");
return Uri.fromFile(file);
} else {
file.createNewFile();
OutputStream os = new FileOutputStream(file);
InputStream is = getActivity().getAssets().open(name);
byte[] buffer = new byte[1024];
int bufferRead = 0;
while((bufferRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bufferRead);
}
os.flush();
is.close();
os.close();
Log.d("Test", "=========copyFile success=========");
return Uri.fromFile(file);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
獲取raw目錄下的資源 返回流和文件路徑
/**
* 獲取raw目錄下的資源
*
* @param resId 資源id
*/
public static InputStream getRawStream(Context context, int resId) {
return context.getResources().openRawResource(resId);
}
/**
* 獲取raw目錄下的資源
*
* @param resId 資源id
*/
public static String getRawFilePath(Context context, int resId) {
return "android.resource://" + context.getPackageName() + "/" + resId;
}
拷貝assets中文件到指定路徑
/**
從assets目錄中復制整個文件夾內容
@param context Context 使用CopyFiles類的Activity
@param oldPath String 原文件路徑 如:/aa
@param newPath String 復制后路徑 如:xx:/bb/cc
*/
public void copyFilesFassets(Context context,String oldPath,String newPath) {
try {
String fileNames[] = context.getAssets().list(oldPath);//獲取assets目錄下的所有文件及目錄名
if (fileNames.length > 0) {//如果是目錄
File file = new File(newPath);
file.mkdirs();//如果文件夾不存在,則遞歸
for (String fileName : fileNames) {
copyFilesFassets(context,oldPath + "/" + fileName,newPath+"/"+fileName);
}
} else {//如果是文件
InputStream is = context.getAssets().open(oldPath);
FileOutputStream fos = new FileOutputStream(new File(newPath));
byte[] buffer = new byte[1024];
int byteCount=0;
while((byteCount=is.read(buffer))!=-1) {//循環從輸入流讀取 buffer字節
fos.write(buffer, 0, byteCount);//將讀取的輸入流寫入到輸出流
}
fos.flush();//刷新緩沖區
is.close();
fos.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
//如果捕捉到錯誤則通知UI線程
MainActivity.handler.sendEmptyMessage(COPY_FALSE);
}
}
以下是完整的工具類代碼 直接拷貝到工程中就可以使用
package com.insworks.lib_datas.utils;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* @ProjectName: AndroidTemplateProject2
* @Package: com.insworks.lib_datas.utils
* @ClassName: AssetsUtil
* @Author: Song Jian
* @CreateDate: 2019/8/8 14:33
* @UpdateUser: 更新者
* @UpdateDate: 2019/8/8 14:33
* @UpdateRemark: 更新說明
* @Version: 1.0
* @Description: Assets和raw文件文件讀取工具類
* <p>
* String[] list(String path);//列出該目錄下的下級文件和文件夾名稱
* <p>
* InputStream open(String fileName);//以順序讀取模式打開文件,默認模式為ACCESS_STREAMING
* <p>
* InputStream open(String fileName, int accessMode);//以指定模式打開文件。讀取模式有以下幾種:
* //ACCESS_UNKNOWN : 未指定具體的讀取模式
* //ACCESS_RANDOM : 隨機讀取
* //ACCESS_STREAMING : 順序讀取
* //ACCESS_BUFFER : 緩存讀取
*/
public class AssetsUtil {
/**
* 獲取assets目錄下的網頁
* 這種方式可以加載assets目錄下的網頁,並且與網頁有關的css,js,圖片等文件也會的加載。
* webView.loadUrl("file:///android_asset/html/index.html");
*
* @param filePath
*/
public static String getHtml(String filePath) {
return "file:///android_asset/" + filePath;
}
/**
* 獲取所有文件
*
* @param path 目錄
* @return
*/
public static String[] getfiles(Context context, String path) {
AssetManager assetManager = context.getAssets();
String[] files = null;
try {
files = assetManager.list(path);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
assetManager.close();
}
return files;
}
/**
* 獲取assets目錄下的圖片資源
*
* @param fileName
*/
public static Bitmap getPic(Context context, String fileName) {
InputStream is = null;
Bitmap bitmap = null;
try {
is = context.getAssets().open(fileName);
bitmap = BitmapFactory.decodeStream(is);
} catch (IOException e) {
e.printStackTrace();
} finally {
close(is);
}
return bitmap;
}
/**
* 關閉流
*
* @param is
*/
private static void close(Closeable... is) {
for (Closeable i : is) {
try {
i.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 獲取assets目錄下的文本資源
*
* @param fileName
*/
public static String getTex(Context context, String fileName) {
InputStream is = null;
String result = "";
try {
is = context.getAssets().open(fileName);
int lenght = is.available();
byte[] buffer = new byte[lenght];
is.read(buffer);
result = new String(buffer, "utf8");
} catch (IOException e) {
e.printStackTrace();
} finally {
close(is);
}
return result;
}
/**
* 獲取assets目錄下的音頻資源
*
* @param fileName
*/
public static AssetFileDescriptor getAudio(Context context, String fileName) {
AssetFileDescriptor afd = null;
try {
// 打開指定音樂文件,獲取assets目錄下指定文件的AssetFileDescriptor對象
afd = context.getAssets().openFd(fileName);
// MediaPlayer mPlayer=new MediaPlayer();
// mPlayer.reset();
// // 使用MediaPlayer加載指定的聲音文件。
// mPlayer.setDataSource(afd.getFileDescriptor(),
// afd.getStartOffset(), afd.getLength());
// // 准備聲音
// mPlayer.prepare();
// // 播放
// mPlayer.start();
} catch (IOException e) {
e.printStackTrace();
} finally {
close(afd);
}
return afd;
}
/**
* 獲取assets目錄下的URI
* 可用於播放視頻資源
*
* @param fileName
*/
public static Uri getUri(Context context, String fileName) {
File file = getFile(context, fileName);
//播放視頻
// VideoView mVideoView = new VideoView(context);
// mVideoView.setVideoURI(Uri.fromFile(file));
// mVideoView.start();
return Uri.fromFile(file);
}
/**
* 將流拷貝到本地 然后返回本地file 默認拷貝到Files目錄
*
* @param context
* @param name
* @return
*/
public static File getFile(Context context, String name) {
InputStream is = null;
FileOutputStream os = null;
try {
File dir = context.getFilesDir();
File file = new File(dir, name);
if (file.exists()) {
return file;
} else {
file.createNewFile();
os = new FileOutputStream(file);
is = context.getAssets().open(name);
byte[] buffer = new byte[1024];
int bufferRead = 0;
while ((bufferRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bufferRead);
}
os.flush();
is.close();
os.close();
Log.d("Test", "=========getFile success=========");
return file;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
close(is, os);
}
return null;
}
/**
* 獲取raw目錄下的資源
*
* @param resId 資源id
*/
public static InputStream getRawStream(Context context, int resId) {
return context.getResources().openRawResource(resId);
}
/**
* 獲取raw目錄下的資源
*
* @param resId 資源id
*/
public static String getRawFilePath(Context context, int resId) {
return "android.resource://" + context.getPackageName() + "/" + resId;
}
/**
* 從assets目錄中復制內容到sd卡中
*
* @param context Context 使用CopyFiles類的Activity
* @param assetPath String 原文件路徑 如:/aa
* @param newPath String 復制后路徑 如:xx:/bb/cc
*/
public static void copyFilesFassets(Context context, String assetPath, String newPath) {
InputStream is = null;
FileOutputStream fos = null;
try {
String fileNames[] = context.getAssets().list(assetPath);//獲取assets目錄下的所有文件及目錄名
if (fileNames.length > 0) {//如果是目錄
File file = new File(newPath);
file.mkdirs();//如果文件夾不存在,則遞歸
for (String fileName : fileNames) {
copyFilesFassets(context, assetPath + "/" + fileName, newPath + "/" + fileName);
}
} else {//如果是文件
is = context.getAssets().open(assetPath);
fos = new FileOutputStream(new File(newPath));
byte[] buffer = new byte[1024];
int byteCount = 0;
while ((byteCount = is.read(buffer)) != -1) {//循環從輸入流讀取 buffer字節
fos.write(buffer, 0, byteCount);//將讀取的輸入流寫入到輸出流
}
fos.flush();//刷新緩沖區
is.close();
fos.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
//如果捕捉到錯誤則通知UI線程
} finally {
close(is, fos);
}
}
}
關於我
微信公眾號:infree6 或者直接掃碼