您的位置:首页 > 移动开发 > Android开发

删除Android工程中冗余资源

2015-10-30 18:30 483 查看
最近精简工程中的资源,在长时间开发过程中会冗余很多资源文件,如果手动删除,太耗时间。Android中提供了一个lint工具,可以帮助我们找到未使用的资源文件和未使用的value中的属性。下面介绍步骤:

1、在window的cmd中使用:

lint --check "UnusedResources" E:\myWorkspace\myapp > D:\result.txt

result.txt 默认路径c:\Users\[UserName]

记得将命令中的路径更换成自己工程的路径

解释:使用lint命令,将工程myapp中res文件夹下未使用到的资源文件的信息,输入到D盘下的result.txt文件中

注意:生成的result.txt文件使用windows自带的记事本打开时,会出现换行异常;所以应使用EditPlus等软件打开!!!




  2、自己写个方法读取result.txt中的内容,然后使用代码删除冗余文件。

方法如下:


 /**
* 删除 未使用的冗余资源
*
* @param bool 是否删除文件
* @throws Exception
*/
private static void deleteRes(boolean bool) throws Exception {

String encoding = "UTF-8"; // 字符格式
String projectPath = "E:\\myWorkspace\\myapp\\"; //Android工程所在地址
String filePath1 = "D:\\"; //result的所在路径
File file = new File(filePath, "result.txt"); //获取result.txt 文件 生成地址
if (file.isFile() && file.exists()) {// 判断文件是否存在
InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
//该判断是筛选文件的条件,根据自己的需求修改
if (line.contains("UnusedResources") && !line.contains("res\\value") && !line.contains("appcompat")
&& !line.contains("res\\xml")&& !line.contains("res\\raw")&& !line.contains("res\\menu")) {
// System.out.println(line);
int end = line.indexOf(":");
if (end != -1) {
String file_end = line.substring(0, end);
String f = projectPath + file_end;
System.out.println(f); //打印冗余文件路径
if (bool) {
boolean delete = new File(f).delete();
System.out.println("delete " +delete+ " !!!!!"); //输出删除信息
}
}

}

}
read.close();
}
}


将projectPath、filePath修改成自己的路径,注意最后面必须要有两个斜线!!!!!!否则拼出的路径会少一个斜线,造成错误!!!!

3、使用上面方法可以删除冗余文件。

注意:

1、该方法中会打印冗余文件路径 和删除是否成功信息

2、多次运行上面的类,进行多次删除,直到控制台没有任何打印信息为止,才能将冗余文件删除干净。原因:由于一次删除之后,可能将某些文件的引用删掉了,可能产生新的冗余文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: