开发web应用时,有时更新了类却没有生效,其实是因为jboss/tomcat中其他发布包下有同名类(包括全路径都相同)。

于是萌发了做个程序来检查指定目录是否存在重复类(通过asm从类文件中取类的全路径),扩展开来,还支持查找重复的文件(按文件md5进行比较),重复的jar文件。

主要代码如下:

package cn.jerryhouse.util.dup_files;

import java.io.File;

public abstract class FileProcessor {
private long totalFileCount = 0;
private long processedFileCount = 0;
public void processFiles(File[] dirs) throws Exception {
for (File file : dirs) {
processFile(file);
}
} public void processFile(File file) throws Exception {
if (file.isFile()) {
if (isFileAccepted(file)) {
handleFile(file);
processedFileCount++;
}
totalFileCount++;
} else {
File[] files = file.listFiles();
for (File fileInDir : files) {
processFile(fileInDir);
}
}
} protected boolean isFileAccepted(File file) throws Exception {
return true;
} protected abstract void handleFile(File file); public long getTotalFileCount() {
return totalFileCount;
} public long getProcessedFileCount() {
return processedFileCount;
}
}

package cn.jerryhouse.util.dup_files;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap; public class FileDupFinder extends FileProcessor {
protected Map<String, List<String>> fileMap = new ConcurrentHashMap<String, List<String>>();
public void analyseResult() {
boolean foundDup = false;
for (Entry<String, List<String>> entry : fileMap.entrySet()) {
List<String> classPathList = entry.getValue();
if (classPathList.size() > 1) {
System.out.println(" paths:"
+ classPathList);
foundDup = true;
}
}
if (foundDup == false) {
System.out.println("No duplicate file found.");
}
} protected void handleFile(final File file) {
try {
String fileMD5 = FileDigest.getFileMD5(file);
try {
List<String> list;
if (fileMap.get(fileMD5) != null) {
list = fileMap.get(fileMD5);
list.add(file.getCanonicalPath());
} else {
list = new LinkedList<String>();
list.add(file.getCanonicalPath());
fileMap.put(fileMD5, list);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} }

package cn.jerryhouse.util.dup_files;

import java.io.File;

public class JarFileDupFinder extends FileDupFinder {

	protected boolean isFileAccepted(final File file) throws Exception
{
if(file.getCanonicalPath().endsWith(".jar"))
{
return true;
}
else
{
return false;
}
} }
package cn.jerryhouse.util.dup_files;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry; import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor; public class ClassDupFinder extends FileDupFinder { protected boolean isFileAccepted(final File file) throws Exception {
if (file.getCanonicalPath().endsWith(".class")) {
return true;
} else {
return false;
}
} public void analyseResult() {
boolean foundDup = false;
for (Entry<String, List<String>> entry : fileMap.entrySet()) {
List<String> classPathList = entry.getValue();
if (classPathList.size() > 1) {
System.out.println("class:" + entry.getKey() + " paths:"
+ classPathList);
foundDup = true;
}
}
if (foundDup == false) {
System.out.println("No duplicate class found.");
}
} protected void handleFile(final File file) {
try {
String filePath = file.getCanonicalPath();
ClassVisitor visitor = new ClassVisitor() {
@Override
public void visit(int version, int access, String name,
String signature, String superName, String[] interfaces) {
try {
List<String> list;
if (fileMap.get(name) != null) {
list = fileMap.get(name);
list.add(file.getCanonicalPath());
} else {
list = new LinkedList<String>();
list.add(file.getCanonicalPath());
fileMap.put(name, list);
}
} catch (IOException e) {
e.printStackTrace();
}
} @Override
public void visitSource(String source, String debug) {
} @Override
public void visitOuterClass(String owner, String name,
String desc) {
} @Override
public AnnotationVisitor visitAnnotation(String desc,
boolean visiable) {
return null;
} @Override
public void visitAttribute(Attribute attr) {
} @Override
public void visitInnerClass(String name, String outerName,
String innerName, int access) {
} @Override
public FieldVisitor visitField(int access, String name,
String desc, String signature, Object value) {
return null;
} @Override
public MethodVisitor visitMethod(int access, String name,
String desc, String signature, String[] exceptions) {
return null;
} @Override
public void visitEnd() {
}
};
ClassReader cr = new ClassReader(new FileInputStream(filePath));
cr.accept(visitor, 0);
} catch (Exception e) {
e.printStackTrace();
}
} }
package cn.jerryhouse.util.dup_files;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map; public class FileDigest {
/**
* 获取单个文件的MD5值
* @param file
*/
public static String getFileMD5(File file) {
if (!file.isFile()) {
return null;
}
MessageDigest digest = null;
FileInputStream in = null;
byte buffer[] = new byte[1024];
int len;
try {
digest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
while ((len = in.read(buffer, 0, 1024)) != -1) {
digest.update(buffer, 0, len);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
} /**
* 获取文件夹中文件的MD5值
* @param file
* @param listChild 为true时,递归子目录中的文件;否则不递归
*/
public static Map<String, String> getDirMD5(File file, boolean listChild) {
if (!file.isDirectory()) {
return null;
}
Map<String, String> map = new HashMap<String, String>();
String md5;
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++) {
File f = files[i];
if (f.isDirectory() && listChild) {
map.putAll(getDirMD5(f, listChild));
} else {
md5 = getFileMD5(f);
if (md5 != null) {
map.put(f.getPath(), md5);
}
}
}
return map;
}
}
package cn.jerryhouse.util.dup_files;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader; public abstract class LineReaderProcessor extends FileProcessor {
private long totalFileCount = 0;
private long processedFileCount = 0;
public void processFiles(File[] dirs) throws Exception {
for (File file : dirs) {
processFile(file);
}
} public void processFile(File file) throws Exception {
if (file.isFile()) {
if (isFileAccepted(file)) {
handleFile(file);
}
} else {
File[] files = file.listFiles();
for (File fileInDir : files) {
processFile(fileInDir);
}
}
} protected boolean isFileAccepted(File file) throws Exception {
return true;
} protected void handleFile(File file)
{
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while((line=br.readLine())!=null)
{
readLine(file,line);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
protected abstract void readLine(File file,String line); public long getTotalFileCount() {
return totalFileCount;
} public long getProcessedFileCount() {
return processedFileCount;
}
}
package cn.jerryhouse.util.dup_files;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.UUID; public abstract class LineUpdateProcessor extends FileProcessor {
private long totalFileCount = 0;
private long processedFileCount = 0;
private String NEW_LINE = System.getProperty("line.separator");
public void processFiles(File[] dirs) throws Exception {
for (File file : dirs) {
processFile(file);
}
} public void processFile(File file) throws Exception {
if (file.isFile()) {
if (isFileAccepted(file)) {
handleFile(file);
}
} else {
File[] files = file.listFiles();
for (File fileInDir : files) {
processFile(fileInDir);
}
}
} protected boolean isFileAccepted(File file) throws Exception {
return true;
} protected void handleFile(File file)
{
try {
BufferedReader br = new BufferedReader(new FileReader(file));
File tmpFile = new File(tmpFilePath(file));
BufferedWriter bw = new BufferedWriter(new FileWriter(tmpFile));
String line;
while((line=br.readLine())!=null)
{
String updatedLine = updateLine(file,line);
bw.write(updatedLine+NEW_LINE);
}
br.close();
bw.close();
file.delete();
tmpFile.renameTo(file);
} catch (Exception e) {
e.printStackTrace();
}
} private String tmpFilePath(File file)
{
String dir = file.getParent();
String filePath = dir+""+getUniqFileName();
return filePath;
} private String getUniqFileName()
{
return UUID.randomUUID().toString();
}
protected abstract String updateLine(File file,String line); public long getTotalFileCount() {
return totalFileCount;
} public long getProcessedFileCount() {
return processedFileCount;
}
}

简单测试代码:

package cn.jerryhouse.util.dup_files.test;

import java.io.File;

import org.junit.Test;

import cn.jerryhouse.util.dup_files.ClassDupFinder;
import cn.jerryhouse.util.dup_files.FileDupFinder;
import cn.jerryhouse.util.dup_files.JarFileDupFinder; public class DupTest { @Test
public void testJarFiles() {
try {
File[] files = new File[1];
files[0] = new File("E:\\workspace\\yinxing");
JarFileDupFinder dupFinder = new JarFileDupFinder();
dupFinder.processFiles(files);
dupFinder.analyseResult();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testFileDup() {
try {
File[] files = new File[1];
files[0] = new File("E:\\workspace\\yinxing");
FileDupFinder classDupFinder = new FileDupFinder();
classDupFinder.processFiles(files);
classDupFinder.analyseResult();
} catch (Exception e) {
e.printStackTrace();
}
} @Test
public void testClassDup() {
try {
File[] files = new File[1];
files[0] = new File("E:\\workspace\\yinxing");
ClassDupFinder classDupFinder = new ClassDupFinder();
classDupFinder.processFiles(files);
classDupFinder.analyseResult();
} catch (Exception e) {
e.printStackTrace();
}
} }

注:依赖jar包asm.jar。



java查找重复类/jar包/普通文件的更多相关文章

  1. java查找反复类/jar包/普通文件

    开发web应用时,有时更新了类却没有生效,事实上是由于jboss/tomcat中其它公布包下有同名类(包含全路径都同样). 于是萌发了做个程序来检查指定文件夹是否存在反复类(通过asm从类文件里取类的 ...

  2. Java实现动态修改Jar包内文件内容

    import java.io.*; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; ...

  3. Java如何快速修改Jar包里的文件内容

    需求背景:写了一个实时读取日志文件以及监控的小程序,打包成了Jar包可执行文件,通过我们的web主系统上传到各个服务器,然后调用ssh命令执行.每次上传前都要通过解压缩软件修改或者替换里面的配置文件, ...

  4. Jar中的Java程序如何读取Jar包中的资源文件

    Jar中的Java程序如何读取Jar包中的资源文件 比如项目的组织结构如下(以idea中的项目为例): |-ProjectName |-.idea/  //这个目录是idea中项目的属性文件夹 |-s ...

  5. java中最常用jar包的用途说明

    java中最常用jar包的用途说明,适合初学者 jar包 用途 axis.jar SOAP引擎包 commons-discovery-0.2.jar 用来发现.查找和实现可插入式接口,提供一些一般类实 ...

  6. Java中常见的jar包及其主要用途

    jar包        用途 axis.jar     SOAP引擎包 commons-discovery-0.2.jar     用来发现.查找和实现可插入式接口,提供一些一般类实例化.单件的生命周 ...

  7. Java命令行启动jar包更改默认端口以及配置文件的几种方式

    Java命令行启动jar包更改默认端口以及配置文件的几种方式 java -jar xxx.jar --server.port=8081 默认如果jar包没有启动文件,可以采用这种方式进行启动 java ...

  8. Java学习-039-源码 jar 包的二次开发扩展实例(源码修改)

    最近在使用已有的一些 jar 包时,发现有些 jar 包中的一些方法无法满足自己的一些需求,例如返回固定的格式,字符串处理等等,因而需要对原有 jar 文件中对应的 class 文件进行二次开发扩展, ...

  9. 【转载】JAVA SpringBoot 项目打成jar包供第三方引用自动配置(Spring发现)解决方案

    JAVA SpringBoot 项目打成jar包供第三方引用自动配置(Spring发现)解决方案 本文为转载,原文地址为:https://www.cnblogs.com/adversary/p/103 ...

随机推荐

  1. C# 二分查询

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  2. python lcd 时间显示

    #!/usr/bin/python # QStopWatch -- a very simple stop watch # Copyright (C) 2006 Dominic Battre <d ...

  3. IOS 缩放图片常用方法

    /** * 指定Size压缩图片 (图片会压缩变形) * * @param image 原图 * @param size 压缩size * * @return 压缩后的图片 */ -(UIImage* ...

  4. Swift 2.0 封装图片折叠效果

    文/猫爪(简书作者)原文链接:http://www.jianshu.com/p/688c491580e3著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”. 用Swift封装图片折叠效果 b ...

  5. 线程、线程句柄、线程ID

     什么是句柄:句柄是一种指向指针的指针.我们知道,所谓指针是一种内存地址.应用程序启动后,组成这个程序的各对象是住留在内存的.如果简单地理解,似乎我们只要获知这个内存的首地址,那么就可以随时用这个地址 ...

  6. 关于SVN版本控制器的问题与解决方法

    1.SVN Working copy is too old 有个.svn的文件夹,去掉在commit试试! 2.中文字符变乱码 尽量不要用中文命名文件,因为很多软件对中文的支持还是有不好的地方.

  7. Android基于WIFI实现电脑和手机间数据传输的技术方案研究

    Android手机和电脑间基于wifi进行数据传输,从技术上讲,主要有两种方案: 一种是通过ftp协议实现,Android手机作为数据传输过程中的ftp服务器: 一种是通过http协议实现.Andro ...

  8. jquery,js常用特效名称

  9. PowerDesigner使用常见问题

    1.在数据库生成表的时候,要求PowerDesigner中设计的表的Name的值要放到数据库中表的描述中,而不是PowerDesigner 中字段的Comment: 具体方法如下:首先将PowerDe ...

  10. 基于webrtc的多人视频会话的demo运行程序

    服务端程序: 该服务程序为windows平台下的程序,使用libevent书写,并集成了UDP的中转程序.(该服务器程序不能和客户端程序运行在同一台PC机电脑,不然服务器程序和客户端程序会抢占同一UD ...