Java小程序

小测试

// 包名不能以java打头
package memo.java.by.eric;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public final class Test {
	public static void main(String[] args){
		System.out.println("c" + 12.3);
		// List
		List<String> list = new ArrayList<String>(200);// List初始化
		System.out.println(list.size());
		// Map
		Map<String, Integer> map = new HashMap<String, Integer>(200);// Map初始化
		System.out.println(map.size());

		// 四舍五入取整示例
		System.out.println("四舍五入取整:(2.5)="
				+ new BigDecimal("2.5").setScale(0, BigDecimal.ROUND_HALF_UP));// 3
		System.out.println("四舍五入取整:(1.2)="
				+ new BigDecimal("1.2").setScale(0, BigDecimal.ROUND_HALF_UP));// 1

		// Java运行栈信息示例
		// StackTraceElement[] sa = (new Throwable()).getStackTrace();
		StackTraceElement[] sa = Thread.currentThread().getStackTrace();
		for (int i = 0; i < sa.length; i++) {
			StackTraceElement ste = sa[i];
			System.out.println("at " + ste.getClassName() + "."
					+ ste.getMethodName() + "(" + ste.getFileName() + ":"
					+ ste.getLineNumber() + ")");
		}

		// 布尔类型值判断,下面两种写法均可
		// if(b==true)
		// if(b)
	}
}

控制台输入

package memo.java.by.eric;

import java.util.Scanner;

public class TestScanner {
	public static void main(String[] args){
		@SuppressWarnings("resource")
		Scanner scanner = new Scanner(System.in);
		System.out.println("请输入字符串:");
		while(true){
			String line = scanner.nextLine();
			if(line.equals("exit"))//输入exit时,程序退出
				break;
			System.out.println(">>"+line);
		}
	}
}

Base64加密/解密

package memo.java.by.eric;

import org.apache.commons.codec.binary.Base64;

/**
 * commons-codec官方地址 - http://commons.apache.org/codec/
 * TestBase64
 */
public class TestBase64 {
	/**
	 * Base64加密
	 * @param plainText
	 * @return
	 */
	public String encodeStr(String plainText) {
		byte[] b = plainText.getBytes();
		Base64 base64 = new Base64();
		b = base64.encode(b);
		String s = new String(b);
		return s;
	}
	
	/**
	 * Base64解密
	 * @param encodedText
	 * @return
	 */
	public String decodeStr(String encodedText) {
		byte[] b = encodedText.getBytes();
		Base64 base64 = new Base64();
		b = base64.decode(b);
		String s = new String(b);
		return s;
	}
	
	public static void main(String[] args){
		TestBase64 t = new TestBase64();
		System.out.println("encode [Hello World]: "+t.encodeStr("Hello World"));
		System.out.println("decode [SGVsbG8gV29ybGQ=]: "+t.decodeStr("SGVsbG8gV29yZA=="));
	}
}

文件操作

package memo.java.by.eric;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;

public class TestFileOperation {
	/**
	 * 文本文件拷贝
	 */
	public void textCopy(){
		File f1 = new File("C:\\1.txt");
		File f2 = new File("C:\\1_copy.txt");
		String line = "";
		try {
			FileReader reader = new FileReader(f1);
			FileWriter writer = new FileWriter(f2, true);
			BufferedReader br = new BufferedReader(reader);
			BufferedWriter bw = new BufferedWriter(writer);
			
			int cnt = 0;
			while ((line = br.readLine()) != null) {
				cnt++;
				bw.write(line);
				bw.flush();
				bw.newLine();//换行
			}
			reader.close();
			writer.close();
			System.out.println(cnt+" lines copied.");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 列出指定目录下的所有文件及文件夹
	 * @param dirName
	 */
	public void listAllFiles(String dirName) {
		// 如果dir不以文件分隔符结尾,自动添加文件分隔符
		if (!dirName.endsWith(File.separator)) {
			dirName = dirName + File.separator;
		}
		File dirFile = new File(dirName);
		// 如果dir对应的文件不存在,或者不是一个文件夹则退出
		if (!dirFile.exists() || (!dirFile.isDirectory())) {
			System.out.println("List失败!找不到目录:" + dirName);
		}

		// 列出文件夹下所有的文件
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			if (files[i].isFile()) {
				System.out.println(files[i].getAbsolutePath());
			} else if (files[i].isDirectory()) {
				System.out.println(files[i].getAbsolutePath());
				listAllFiles(files[i].getAbsolutePath());
			}
		}
	}
	
	/**
	 * 列出指定目录下的所有文件及文件夹
	 * @param dirName
	 */
	public void listAllFiles(String dirName, String postfix) {
		// 如果dir不以文件分隔符结尾,自动添加文件分隔符
		if (!dirName.endsWith(File.separator)) {
			dirName = dirName + File.separator;

		}
		File dirFile = new File(dirName);
		// 如果dir对应的文件不存在,或者不是一个文件夹则退出
		if (!dirFile.exists() || (!dirFile.isDirectory())) {
			System.out.println("List失败!找不到目录:" + dirName);
		}

		// 列出文件夹下所有的文件
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			if (files[i].isFile()&&files[i].getName().endsWith(postfix)) {
				System.out.println(files[i].getAbsolutePath());
			} else if (files[i].isDirectory()) {
				listAllFiles(files[i].getAbsolutePath(), postfix);
			}
		}
	}
	
	public static void main(String[] args) {
		TestFileOperation t = new TestFileOperation();
		t.listAllFiles("D:","jpg");
	}
}

JDBC

package memo.java.by.eric;

import java.sql.Connection;
import java.sql.DriverManager; 
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestJDBC {
	//驱动程序,即在classpath中配置的JDBC的驱动程序的JAR包
	//MySQL - com.mysql.jdbc.Driver
	//Oracle -  oracle.jdbc.driver.OracleDriver
	//SQL Server2005 - com.microsoft.sqlserver.jdbc.SQLServerDriver
	//DB2 - com.ibm.db2.jdbc.app.DB2Driver
	//Sybase - com.sybase.jdbc.SybDriver
	//Informix - com.informix.jdbc.IfxDriver
	//PostgreSQL - org.postgresql.Driver
	//以MySQL为例
    public static final String DBDRIVER = "com.mysql.jdbc.Driver"; 
    
    //连接地址是由各个数据库生产商单独提供的,所以需要单独记住  
    //MySQL - jdbc:mysql://localhost:3306/mysql
  	//Oracle -  jdbc:oracle:thin:@localhost:1521:orcl
  	//SQL Server2005 - jdbc:sqlserver://localhost:1433;DatabaseName=myDB
    //DB2 - jdbc:db2://localhost:5000/sample
    //Sybase - jdbc:sybase:Tds:localhost:5007/myDB
    //未测试
    //Informix - jdbc:informix-sqli://localhost:1533/myDB:informixserver=myserver;user=testuser;password=testpassword
    //PostgreSQL - jdbc:postgresql://localhost/myDB
    
    //以MySQL为例
    public static final String DBURL = "jdbc:mysql://localhost:3306/mysql";
    
    //连接数据库的用户名  
    public static final String DBUSER = "root";
    //连接数据库的密码  
    public static final String DBPASS = "111111";
    
    public void demo(){
    	try{
    		Connection con = null; //表示数据库的连接对象
            Statement stmt = null; //表示数据库操作,Statement用于执行不带参数的简单 SQL 语句
            ResultSet result = null; //表示数据库的查询结果
            Class.forName(DBDRIVER); //1、使用CLASS 类加载驱动程序
            con = DriverManager.getConnection(DBURL,DBUSER,DBPASS); //2、连接数据库
            stmt = con.createStatement(); //3、Statement 接口需要通过Connection 接口进行实例化操作
            result = stmt.executeQuery("select host,user from user"); //执行SQL 语句,查询数据库
            System.out.println("[User Info]");
            while (result.next()){  
                String host = result.getString("host");
                String user = result.getString("user");  
                System.out.println("host:"+host+"|user:"+user); 
    		}
    		result.close();
    		stmt.close();
    		con.close(); // 4、关闭数据库
    	}catch(ClassNotFoundException e){
    		System.out.println("加载JDBC驱动程序出错!");
    		e.printStackTrace();
    	}catch(SQLException e){
    		System.out.println("数据库异常!");
    		e.printStackTrace();
    	}
    }
    
    public static void main(String[] args) throws Exception {
    	TestJDBC tj = new TestJDBC();
    	tj.demo();
    }
}

log4j测试

package memo.java.by.eric;

import org.apache.log4j.Logger;
//import org.apache.log4j.PropertyConfigurator;

public class TestLog4j {
	private static Logger logger = Logger.getLogger(TestLog4j.class);
	
	public static void main(String[] agrs){
		// PropertyConfigurator.configure(properties);
		// 记录debug级别的信息  
        logger.debug("This is debug message.");  
        // 记录info级别的信息  
        logger.info("This is info message.");  
        // 记录error级别的信息  
        logger.error("This is error message."); 
	}
}
log4j.properties

log4j.rootLogger=debug,appender1
log4j.appender.appender1=org.apache.log4j.ConsoleAppender
log4j.appender.appender1.layout=org.apache.log4j.PatternLayout
log4j.appender.appender1.layout.ConversionPattern=[%d{yy/MM/dd HH:mm:ss}][%C-%M] %m%n

操作属性文件

package memo.java.by.eric;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;

public class TestProperties {
	public void readProperties(){
		Properties prop = new Properties();
        InputStream in = Object.class.getResourceAsStream("/read.properties"); 
        try {   
            prop.load(in);//加载流
            in.close();//关闭流
            String username, password;
            username = prop.getProperty("username");
            password = prop.getProperty("password");
            System.out.println("[read from properties file]");
            System.out.println("username:"+username);
            System.out.println("password:"+password);
        } catch (IOException e) {  
            e.printStackTrace();
        }  
	}
	
	public void writeProperties(){
		Properties prop = new Properties();
		try{
			OutputStream out = new FileOutputStream("/write.properties");
			//this.getClass().getClassLoader().
			prop.setProperty("username", "test");
			prop.setProperty("password", "123456");
			prop.store(out, "author:eric");
			System.out.println("[write to properties file]");
			out.close();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	
	public void readPropertiesFromXML(){
		Properties prop = new Properties();
        InputStream in = Object.class.getResourceAsStream("/read.xml");
		// InputStream in = this.getClass().getClassLoader().getResourceAsStream("/read.xml");// 从Class根目录读取
        // InputStream in = this.getClass().getResourceAsStream("/read.xml");// 从Class所在目录读取
        
        try {   
            prop.loadFromXML(in);//加载流
            in.close();//关闭流
            String username, password;
            username = prop.getProperty("username");
            password = prop.getProperty("password");
            System.out.println("[read from xml file]");
            System.out.println("username:"+username);
            System.out.println("password:"+password);
        } catch (InvalidPropertiesFormatException e){
        	e.printStackTrace();
        } catch (IOException e) {  
            e.printStackTrace();
        }
	}
	
	public void writePropertiesToXML(){
		Properties prop = new Properties();
		try{
			OutputStream out = new FileOutputStream("/write.xml");
			//this.getClass().getClassLoader().
			prop.setProperty("username", "test");
			prop.setProperty("password", "123456");
			prop.storeToXML(out, "author:eric");
			System.out.println("[write to xml file]");
			out.close();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args){
		TestProperties tp = new TestProperties();
		tp.readProperties();
		tp.writeProperties();
		tp.readPropertiesFromXML();
		tp.writePropertiesToXML();
	}
}
read.properties

username=test
password=123456
read.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="username">test</entry>
<entry key="password">123456</entry>
</properties>
正则表达式处理示例
package memo.java.by.eric;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * 正则表达式处理示例
 *
 */
public class TestRegex {
	public static void main(String[] args) {
		//定义模式
		Pattern pattern = Pattern.compile("a\\sb.*c");// space: " " or "\\s"
		//定义匹配器
		Matcher matcher = pattern.matcher("hello a b123c world!");
		//匹配检测, 整个输入序列与该模式匹配时, 才返回true
		System.out.println(matcher.matches());//false
		//如果找到匹配的子字符串,则打印出来
		if(matcher.find()){
			System.out.println(matcher.group());//a b123c
		}
		//也可直接进行模式匹配
		boolean b = Pattern.matches("a*b", "aaab");  
        System.out.println(b);//true
	}
}

package memo.java.by.eric;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * 正则表达式处理示例2
 *
 */
public class TestRegex2 {
	public static void main(String[] args) {
		Pattern p = Pattern.compile("a(.+?)c");
		Matcher m = p.matcher("abcaddcacd");
		while (m.find()) {
			String s = m.group();
			//group是针对()来说的
			//group(0)指匹配出的整个串
			String s0 = m.group(0);
			//group(1)指的是第1个括号里的东西
			String s1 = m.group(1);
			//依次输出:
			//abc||abc||b
			//addc||addc||dd
			System.out.println(s + "||" + s0 + "||" + s1);
		}
		//匹配器重置输入序列
		m.reset("axxc!");
		while (m.find()) {
			System.out.println(m.group());//axxc
		}
	}
}

定时任务

package memo.java.by.eric;

import java.util.TimerTask;
import java.util.Timer;

/**
 * 使用TimerTask和Timer实现定时任务
 * @author Administrator
 *
 */
class TestTimerTask extends TimerTask {
	public void run() {
		System.out.println("run!");
	}
}

public class TestTimer {
	public static void main(String[] args) {
		// 设为true时, 此timer以daemon方式运行(优先级低,程序结束后,timer也自动结束)
		Timer timer = new Timer(false);
		// 程序运行1s后,每隔两秒执行
		timer.schedule(new TestTimerTask(), 1000, 2000);
	}
}


获取本机MAC地址

package eric.test;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class MacInfoTest {
	/**
	 * 获取所有网卡的MAC地址
	 * @return
	 */
	public static List<String> getAllMac() {
		List<String> list = new ArrayList<String>();
		try {
			// 返回所有网络接口的一个枚举实例
			Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
			while (e.hasMoreElements()) {
				// 获得当前网络接口
				NetworkInterface network = e.nextElement();
				if (network != null) {
					if (network.getHardwareAddress() != null) {
						// 获得MAC地址
						// 结果是一个byte数组,每项是一个byte,我们需要通过parseByte方法转换成常见的十六进制表示
						byte[] address = network.getHardwareAddress();
						StringBuffer sb = new StringBuffer();
						if (address != null && address.length > 1) {
							sb.append(parseByte(address[0])).append(":").append(parseByte(address[1])).append(":")
									.append(parseByte(address[2])).append(":").append(parseByte(address[3])).append(":")
									.append(parseByte(address[4])).append(":").append(parseByte(address[5]));
							if (!"00:00:00:00:00:00".equals(sb.toString())) {
								list.add(sb.toString().toUpperCase());
							}
						}
					}
				} else {
					System.out.println("获取MAC地址发生异常");
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return list;
	}

	private static String parseByte(byte b) {
		String s = "00" + Integer.toHexString(b);
		return s.substring(s.length() - 2);
	}

	public static void main(String[] args) {
		System.out.println("本地MAC地址:");
		List<String> list = getAllMac();
		for (String mac : list) {
			System.out.println(mac);
		}
	}
}

MD5加密

package eric.test;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Test {
    public static final int MD5_32_UPPER = 1;// 32位大写
    public static final int MD5_32_LOWER = 2;// 32位小写(默认)
    public static final int MD5_16_UPPER = 3;// 16位大写
    public static final int MD5_16_LOWER = 4;// 16位小写
    
	/**
	 * MD5 32位小写
	 * @param str
	 * @return
	 */
	public static String md5encode32(String str){
		String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes("UTF-8"));
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
        } catch (NoSuchAlgorithmException e) {
        	e.printStackTrace();
        } catch (Exception e) {
        	e.printStackTrace();
		}
        return result;
	}
	
	/**
	 * MD5 16位小写
	 * @param str
	 * @return
	 */
	public static String md5encode16(String str){
		// 中间16位
		return md5encode32(str).substring(8, 24);
	}
	
	public static String getMD5Str(String plainText, int encType) {
		String cipherText;

		switch (encType) {
		case MD5_32_UPPER:
			cipherText = md5encode32(plainText).toUpperCase();
			break;
		case MD5_32_LOWER:
			cipherText = md5encode32(plainText);
			break;
		case MD5_16_UPPER:
			cipherText = md5encode16(plainText).toUpperCase();
			break;
		case MD5_16_LOWER:
			cipherText = md5encode16(plainText);
			break;
		default:
			cipherText = "";
		}

		return cipherText;
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println("MD5(hello, MD5_32_UPPER) = " + getMD5Str("hello", MD5_32_UPPER));
		System.out.println("MD5(hello, MD5_32_LOWER) = " + getMD5Str("hello", MD5_32_LOWER));
		System.out.println("MD5(hello, MD5_16_UPPER) = " + getMD5Str("hello", MD5_16_UPPER));
		System.out.println("MD5(hello, MD5_16_LOWER) = " + getMD5Str("hello", MD5_16_LOWER));
	}

}

AES加密

package eric.test;

import java.security.SecureRandom;


import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;


import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


public class EncryptAesUtil {
    private final static String CIPHER_AES = "AES";
    private final static String ENCRYPT_KEY = "HelloWorld";
    private final static String CHARSET_UTF_8 = "utf-8";


    /**
     * AES加密为base 64 code
     *
     * @param content
     *            待加密的内容
     * @return 加密后的base 64 code
     * @throws Exception
     */
    public static String aesEncrypt(String content) throws Exception {
        String cipherText = base64Encode(aesEncryptToBytes(content, ENCRYPT_KEY));
        return base64Encode(cipherText.getBytes(CHARSET_UTF_8));
    }


    /**
     * AES加密为base 64 code
     *
     * @param content
     *            待加密的内容
     * @param encryptKey
     *            加密密钥
     * @return 加密后的base 64 code
     * @throws Exception
     */
    public static String aesEncrypt(String content, String encryptKey) throws Exception {
        String cipherText = base64Encode(aesEncryptToBytes(content, encryptKey));
        return base64Encode(cipherText.getBytes(CHARSET_UTF_8));
    }


    /**
     * 将base 64 code AES解密
     *
     * @param encryptStr
     *            待解密的base 64 code
     * @return 解密后的string
     * @throws Exception
     */
    public static String aesDecrypt(String encryptStr) throws Exception {
        String cipherText = new String(base64Decode(encryptStr), CHARSET_UTF_8);
        return aesDecryptByBytes(base64Decode(cipherText), ENCRYPT_KEY);
    }


    /**
     * 将base 64 code AES解密
     *
     * @param encryptStr
     *            待解密的base 64 code
     * @param encryptKey
     *            解密密钥
     * @return 解密后的string
     * @throws Exception
     */
    public static String aesDecrypt(String encryptStr, String encryptKey) throws Exception {
        String cipherText = new String(base64Decode(encryptStr), CHARSET_UTF_8);
        return aesDecryptByBytes(base64Decode(cipherText), encryptKey);
    }


    /**
     * AES加密
     *
     * @param content
     *            待加密的内容
     * @param encryptKey
     *            加密密钥
     * @return 加密后的byte[]
     * @throws Exception
     */
    private static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance(CIPHER_AES);
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(encryptKey.getBytes(CHARSET_UTF_8));
        kgen.init(128, random);


        Cipher cipher = Cipher.getInstance(CIPHER_AES);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), CIPHER_AES));


        return cipher.doFinal(content.getBytes(CHARSET_UTF_8));
    }


    /**
     * AES解密
     *
     * @param encryptBytes
     *            待解密的byte[]
     * @param decryptKey
     *            解密密钥
     * @return 解密后的String
     * @throws Exception
     */
    private static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance(CIPHER_AES);
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(decryptKey.getBytes(CHARSET_UTF_8));
        kgen.init(128, random);


        Cipher cipher = Cipher.getInstance(CIPHER_AES);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), CIPHER_AES));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);


        return new String(decryptBytes);
    }


    /**
     * base 64 encode
     *
     * @param bytes
     *            待解码 的byte[]
     * @return 解码后的base 64 code
     */
    private static String base64Encode(byte[] bytes) {
        return new BASE64Encoder().encode(bytes);
    }


    /**
     * base 64 decode
     *
     * @param base64Code
     *            待解码的base 64 code
     * @return 解码后的byte[]
     * @throws Exception
     */
    private static byte[] base64Decode(String base64Code) throws Exception {
        return (base64Code == null || "".equals(base64Code)) ? null : new BASE64Decoder().decodeBuffer(base64Code);
    }


    public static void main(String[] args) throws Exception {
        String content = "Hello,World";
        System.out.println("加密前" + content);


        String encrypt = aesEncrypt(content);
        System.out.println("加密后" + encrypt);


        String decrypt = aesDecrypt(encrypt);
        System.out.println("解密后" + decrypt);
    }
}

日志分析

package eric.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * 日志分析
 *
 */
public class LogAnalysis {
	private String[] logDirs = new String[] { "E:\\error1", "E:\\error2" };// 错误日志的目录
	private ArrayList<String> fileList = new ArrayList<String>();// 错误日志文件列表
	private Map<String, Integer> exceptionStatistics = new HashMap<String, Integer>();// 异常统计

	/**
	 * 初始化日志文件列表
	 */
	private void initFileList() {
		for (String dir : logDirs) {
			File logDir = new File(dir);
			File[] files = logDir.listFiles();
			for (File file : files) {
				// 获取路径下所有文件,不包括下属文件夹及下属文件夹下的文件
				if (file.isFile()) {
					fileList.add(file.getAbsolutePath());
				}
			}
		}
	}

	/**
	 * 遍历日志以收集异常信息
	 */
	private void collectExceptionInfo() {
		for (String fileStr : fileList) {
			File file = new File(fileStr);
			// java.sql.BatchUpdateException: Duplicate entry '99999' for key 'PRIMARY'
			String line = "";
			// java.sql.BatchUpdateException
			String exceptionStr = "";
			Pattern userPattern = Pattern.compile(".+?\\..*?Exception:");
			Matcher userMatcher;
			try {
				FileReader reader = new FileReader(file);
				BufferedReader br = new BufferedReader(reader);
				while ((line = br.readLine()) != null) {
					if (line.startsWith("Caused by:")) {
						continue;
					}
					// 避免正则匹配过慢(设为1000,单行大于1000个字符时,不执行正则匹配)
					if (line.length() > 1000) {
						continue;
					}
					userMatcher = userPattern.matcher(line);
					if (userMatcher.find()) {
						exceptionStr = userMatcher.group();
						String temp = exceptionStr.replace(" ", "");
						if (!(exceptionStr.length() == temp.length())) {
							continue;
						}
						// 去掉冒号
						exceptionStr = exceptionStr.substring(0, exceptionStr.length() - 1);
						// System.out.println(line);
						System.out.println(exceptionStr);
						if (exceptionStatistics.get(exceptionStr) == null) {
							exceptionStatistics.put(exceptionStr, 1);
						} else {
							Integer cnt = exceptionStatistics.get(exceptionStr);
							exceptionStatistics.put(exceptionStr, new Integer(cnt + 1));
						}
					}
					// line = "";
				}
				reader.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 打印异常统计信息
	 */
	private void printStatistics() {
		Iterator<Entry<String, Integer>> iter = exceptionStatistics.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>) iter.next();
			String key = entry.getKey();
			Integer val = entry.getValue();
			System.out.println(key + "\t" + val);
		}
	}

	public void analyze() {
		initFileList();
		collectExceptionInfo();
		printStatistics();
	}

	public static void main(String[] args) {
		LogAnalysis logAnalysis = new LogAnalysis();
		logAnalysis.analyze();
	}

}

将数字转为中文

/**
 * 数字转为中文
 * 将10亿以内的阿拉伯数字转成汉字
 */
public class No2Chinese {
	// private static final String[] cnNumbers = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
	private static final String[] cnNumbers = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
	// String series[] = new String[] { "元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿" };
	// String series[] = new String[] { "个", "十", "百", "千", "万", "十", "百", "千", "亿" };
	private static final String series[] = new String[] { "", "十", "百", "千", "万", "十", "百", "千", "亿" };
			
	public static String getCnStr(int number) {
		String s = String.valueOf(number);
		StringBuffer sb = new StringBuffer();
		// 先把数字转为中文
		for (int i = 0; i < s.length(); i++) {
			String index = String.valueOf(s.charAt(i));
			sb = sb.append(cnNumbers[Integer.parseInt(index)]);
		}
		
		String sss = String.valueOf(sb);
		int i = 0;
		// 再加上位符:十、百、千 ...
		for (int j = sss.length(); j > 0; j--) {
			sb = sb.insert(j, series[i++]);
		}
		return sb.toString();
	}

	public static void main(String[] args) {
		System.out.println(getCnStr(912321321));
	}
}

参考资料:
1. 百度知道1
2. 百度知道2

分页工具类

import java.io.Serializable;
import java.util.List;

/**
 * 储存分页处理工具类
 * 在调用此类的方法之前需设置总页数(即得先从数据库查询到相应数据的数据量)
 */
public class Pagination implements Serializable {
    private static final long serialVersionUID = 1231954534613188876L;
    private int start; // start表示当前页开始的记录数, start = (每页行数 * (当前页数 - 1))
    private int end; // 当前页结束的记录行数
    private int totalCount; // 总行数
    private int pageSize = 10; // 每页行数, 默认10
    private int currentPage; // 当前页码
    private List resultList;

    public Pagination() {
        start = 0;
        end = 0;
        currentPage = 1;
        this.totalCount = 0;
    }

    public Pagination(int totalCount) {
        start = 0;
        end = 0;
        currentPage = 1;
        this.totalCount = totalCount;
    }

    public Pagination(int totalCount, Integer numPerPage) {
        start = 0;
        end = 0;
        this.totalCount = totalCount;
        currentPage = 1;
        if (numPerPage != null && numPerPage > 0) {
            pageSize = numPerPage;
        }
    }

    // 得到起始数
    public int getStart() {
        start = pageSize * (currentPage - 1);
        return start;
    }

    // 设置起始数
    public void setStart(int start) {
        if (start < 0) {
            this.start = 0;
        } else if (start >= this.totalCount) {
            this.start = this.totalCount - 1;
        } else {
            this.start = start;
        }
    }

    // 设置当前页的最后一行的在总记录中的顺序(从0开始)
    public void setEnd(int end) {
        this.end = end;
    }

    // 得到当前页的最后一行的在总记录中的顺序(从0开始)
    public int getEnd() {
        if (pageSize * currentPage > this.totalCount) {
            end = this.totalCount - 1;
        } else {
            end = pageSize * currentPage - 1;
        }
        return end;
    }

    // 跳到第一页
    public void gotoFirstPage() {
        currentPage = 1;
    }

    // 跳到最后一页
    public void gotoLastPage() {
        if (this.totalCount % pageSize == 0) {
            currentPage = this.totalCount / pageSize;
        } else {
            currentPage = this.totalCount / pageSize + 1;
        }
    }

    // 跳到指定的某一页
    public void gotoPage(int pageNumber) {
        if ((pageNumber <= 1) || (getTotalCount() < this.getPageSize())) {
            currentPage = 1;
        } else if (pageNumber * pageSize >= this.totalCount) {
            gotoLastPage();
        } else {
            currentPage = pageNumber;
        }
    }

    // 设置总行数
    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    // 得到总行数
    public int getTotalCount() {
        return totalCount;
    }

    // 设置每页行数
    public void setPageSize(int rowsPerPage) {
        this.pageSize = rowsPerPage;
    }

    // 得到每页行数
    public int getPageSize() {
        return pageSize;
    }

    // 得到总页数
    public int getTotalPages() {
        if (this.totalCount % pageSize == 0) {
            return this.totalCount / pageSize;
        } else {
            return this.totalCount / pageSize + 1;
        }
    }

    // 得到当前页数
    public int getCurrentPage() {
        return currentPage;
    }

    // 设置当前页数
    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

	public List getResultList() {
		return resultList;
	}

	public void setResultList(List resultList) {
		this.resultList = resultList;
	}
    
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值