在Android开发中,有时会将文件放到Assets目录下,因为存放在Assets目录下的文件不会在R.java自动生成ID,所以读取/assets目录下的文件必须指定文件的路径。
下面的代码是从Assets目录下读取里面的文件并获得一些信息:
String[] files = null;
try {// 遍历assest文件夹,读取压缩包及安装包
files = getAssets().list("");
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < files.length; i++) {
String fileName = files[i];
Log.i("fileName", " fileName: " + fileName);
if (fileName.contains(".apk")) {//判断是否为Apk
String apkName = fileName;
String s = String.valueOf(this.getCacheDir().getAbsolutePath());//不能直接读取assets目录下的Apk信息,所以需要先将其拷贝出来
final String apkcachePath = (new StringBuilder(s)).append(
"/temp.apk").toString();// 临时文件
if (copyFileFromAssets(this, apkName, apkcachePath)) {
PackageInfo packageInfo = SystemTools.getApkFileInfo(this,
apkcachePath);
ApplicationInfo applicationInfo = packageInfo.applicationInfo;
String apkPackageName = applicationInfo.packageName;//读取Apk包名
// 获取应用的Activity名
PackageManager pm = getPackageManager();
PackageInfo info2 = null;
try {
info2 = getPackageManager().getPackageInfo(
apkPackageName, 0);
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setPackage(info2.packageName);
List
intent, 0);
ResolveInfo ri = apps.iterator().next();
if (ri != null) {
String apkActivityName = ri.activityInfo.name;
}
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
}
if (fileName.contains(".zip")) {//判断是否为Zip包
String zipName = fileName;
AssetManager am = getAssets();
try {
AssetFileDescriptor zipFileDes = am.openFd(zipName);//Zip包名称
String zipSize = zipFileDes.getLength() / (1024 * 1024);//Zip包大小
} catch (IOException e) {
e.printStackTrace();
}
Log.i("", "压缩包大小:" + zipSize);
}
}
下面将assets目录下的文件拷贝到一个临时目录下
public static boolean copyFileFromAssets(Context context, String apkName, String path){
boolean flag = false;
int BUFFER = 10240;
BufferedInputStream in = null;
BufferedOutputStream out = null;
AssetFileDescriptor fileDescriptor = null;
byte b[] = null;
try {
fileDescriptor = context.getAssets().openFd(apkName);
File file = new File(path);
if (file.exists()) {
if (fileDescriptor != null
&& fileDescriptor.getLength() == file.length()) {
flag = true;
} else
file.delete();
}
if (!flag) {
in = new BufferedInputStream(fileDescriptor.createInputStream(),
BUFFER);
boolean isOK = file.createNewFile();
if (in != null && isOK) {
out = new BufferedOutputStream(new FileOutputStream(file),
BUFFER);
b = new byte[BUFFER];
int read = 0;
while ((read = in.read(b)) > 0) {
out.write(b, 0, read);
}
flag = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(out != null){
out.close();
}
if(in != null){
in.close();
}
if(fileDescriptor != null){
fileDescriptor.close();
}
}
return flag;
}
}