Android 删除无用Java文件

项目规模不断地扩大,累积的无用Java文件,也会越来越多,这里我介绍一种清理方法:使用Ucdetector工具删除无用Java文件。

首先,你需要安装Ucdetector插件,配置好report生成目录。

安装成功,你会发现,右键一个project,会出现UCDetector选项,选择该选项的子选项:Detect unncessary code,插件会监测project中的无用Java类,并生成report报告,报告有两种格式html和txt文本,供开发人员查看。

当然了,UCDetector还提供自动删除冗余类功能,但是不推荐这么做,因为该工具,无法监测这三种类:xml中的view类,反射使用的类,作为依赖包被其他project引用的类,建议手动删除,具体情况具体考虑。

考虑到report中不仅仅是无效类,读取的困难,我在这里提供一个java工具类:

package clears;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ClearJava {
	public static final String separator = File.separator;
	
	private static String clearUnusedJavaFile(boolean autoDelete, String inFileName,
			String localProjectPath) throws IOException {

		File infile = new File(inFileName);
		SimpleDateFormat formatter = new SimpleDateFormat(
				"yyyy-MM-dd-HH-mm-ss");
		Date curDate = new Date(System.currentTimeMillis());
		String dateStr = formatter.format(curDate);
		RandomAccessFile outfile = new RandomAccessFile(localProjectPath + separator + "unused_java" + dateStr + ".txt", "rw");
		int index = -1;
		String path = localProjectPath + "/src/";
		BufferedReader bf = new BufferedReader(new FileReader(infile));
		String content = "";
		StringBuilder sb = new StringBuilder();

		while ((content = bf.readLine()) != null) {
			index = content.indexOf(".<init>");
			if (index != -1
					&& (content.indexOf("\tClass") == (content.indexOf(")") + 1) || content
							.indexOf("\tInterface") == (content.indexOf(")") + 1))) {
				String temp = path
						+ content.substring(0, index).replace('.', '/')
						+ ".java";
				System.out.println("unused java file: " + temp);
				
				if (autoDelete) {
					new File(temp).delete();
				}
				sb.append(temp).append("\r\n");
			}
		}
		
		outfile.seek(outfile.length());
		outfile.writeBytes(sb.toString());
		bf.close();
		outfile.close();

		return sb.toString();
	}

	public static void main(String[] args) {
		if (args.length == 2) {
			String inputFile = args[0];
			String localProjectPath = args[1];
			try {
				String str = clearUnusedJavaFile(false, inputFile, localProjectPath);
			} catch (IOException e) {
				System.out.print("something wrong");
			}

		} else {
			System.out.println("arguments wrong!!");
		}

	}
}

运行时需要给出两个参数:

E:/ucdetector_reports/UCDetectorReport_001.txt
E:/work_space/projectname

第一个是Ucdetector生成的txt报告地址,第二个则是项目的路径。

如果你非常确定你的项目可以自动删除,autoDelete可以置为true。

(以上代码,亲自验证并应用,完全可以运行)

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值