超精简的Java常用工具类

tech2022-09-17  92

Java常用工具类

1. jdbcutils2.JedisUtils3. DateUtils4.UuidUtils5.MailUtils(邮件工具类)6. Md5Utils

1. jdbcutils

package cn.itcast.util; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; /** * JDBC工具类 使用Durid连接池 */ public class JDBCUtils { private static DataSource ds ; static { try { //1.加载配置文件 Properties pro = new Properties(); //使用ClassLoader加载配置文件,获取字节输入流 InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"); //druid.properties配置文件 /** driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql:///day23 username=root password=root initialSize=5 maxActive=10 maxWait=3000 */ pro.load(is); //2.初始化连接池对象 ds = DruidDataSourceFactory.createDataSource(pro); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * 获取连接池对象 */ public static DataSource getDataSource(){ return ds; } /** * 获取连接Connection对象 */ public static Connection getConnection() throws SQLException { return ds.getConnection(); } }

2.JedisUtils

jedis.properties配置文件host=127.0.0.1port=6379maxTotal=50maxIdle=10 public class JedisPoolUtil { private static JedisPool jedisPool; private static Jedis jedis; static{ //使用类加载器加载配置文件 InputStream rs = JedisPoolUtil.class.getClassLoader().getResourceAsStream("jedis.properties"); //创建properties对象 Properties pro = new Properties(); try { pro.load(rs); } catch (IOException e) { e.printStackTrace(); } //获取数据,设置到JedisPoolConfig中 JedisPoolConfig config = new JedisPoolConfig(); config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle"))); config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal"))); jedisPool = new JedisPool(config,"localhost",6379); } /** * 获取连接方法 */ public static Jedis getJedis(){ return jedisPool.getResource(); } /** * 关闭Jedis */ public static void close(Jedis jedis) { if (jedis != null) { jedis.close(); } } }

3. DateUtils

public class DateParserT { /** * Date 与 String、long 的相互转换 * @param args */ public static void main(String[] args) { Date dt =new Date(); System.out.println(dt); //格式: Wed Jul 06 09:28:19 CST 2016 //格式:2016-7-6 String formatDate = null; formatDate = DateFormat.getDateInstance().format(dt); System.out.println(formatDate); //格式:2016年7月6日 星期三 formatDate = DateFormat.getDateInstance(DateFormat.FULL).format(dt); System.out.println(formatDate); //格式 24小时制:2016-07-06 09:39:58 DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //HH表示24小时制; formatDate = dFormat.format(dt); System.out.println(formatDate); //格式12小时制:2016-07-06 09:42:44 DateFormat dFormat12 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); //hh表示12小时制; formatDate = dFormat12.format(dt); System.out.println(formatDate); //格式去掉分隔符24小时制:20160706094533 DateFormat dFormat3 = new SimpleDateFormat("yyyyMMddHHmmss"); formatDate = dFormat3.format(dt); System.out.println(formatDate); //格式转成long型:1467770970 long lTime = dt.getTime() / 1000; System.out.println(lTime); //格式long型转成Date型,再转成String: 1464710394 -> ltime2*1000 -> 2016-05-31 23:59:54 long ltime2 = 1464710394; SimpleDateFormat lsdFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date lDate = new Date(ltime2*1000); String lStrDate = lsdFormat.format(lDate); System.out.println(lStrDate); //格式String型转成Date型:2016-07-06 10:17:48 -> Wed Jul 06 10:17:48 CST 2016 String strDate = "2016-07-06 10:17:48"; SimpleDateFormat lsdStrFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date strD = lsdStrFormat.parse(strDate); System.out.println(strD); } catch (ParseException e) { e.printStackTrace(); } } }

4.UuidUtils

/** * 产生UUID随机字符串工具类 */ public final class UuidUtil { private UuidUtil(){} public static String getUuid(){ return UUID.randomUUID().toString().replace("-",""); } /** * 测试 */ public static void main(String[] args) { System.out.println(UuidUtil.getUuid()); System.out.println(UuidUtil.getUuid()); System.out.println(UuidUtil.getUuid()); System.out.println(UuidUtil.getUuid()); } }

5.MailUtils(邮件工具类)

/** * 发邮件工具类 */ public final class MailUtils { private static final String USER = ""; // 发件人称号,同邮箱地址 private static final String PASSWORD = ""; // 如果是qq邮箱可以使户端授权码,或者登录密码 /** * * @param to 收件人邮箱 * @param text 邮件正文 * @param title 标题 */ /* 发送验证信息的邮件 */ public static boolean sendMail(String to, String text, String title){ try { final Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.host", "smtp.qq.com"); // 发件人的账号 props.put("mail.user", USER); //发件人的密码 props.put("mail.password", PASSWORD); // 构建授权信息,用于进行SMTP进行身份验证 Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { // 用户名、密码 String userName = props.getProperty("mail.user"); String password = props.getProperty("mail.password"); return new PasswordAuthentication(userName, password); } }; // 使用环境属性和授权信息,创建邮件会话 Session mailSession = Session.getInstance(props, authenticator); // 创建邮件消息 MimeMessage message = new MimeMessage(mailSession); // 设置发件人 String username = props.getProperty("mail.user"); InternetAddress form = new InternetAddress(username); message.setFrom(form); // 设置收件人 InternetAddress toAddress = new InternetAddress(to); message.setRecipient(Message.RecipientType.TO, toAddress); // 设置邮件标题 message.setSubject(title); // 设置邮件的内容体 message.setContent(text, "text/html;charset=UTF-8"); // 发送邮件 Transport.send(message); return true; }catch (Exception e){ e.printStackTrace(); } return false; } public static void main(String[] args) throws Exception { // 做测试用 MailUtils.sendMail("itcast_xian@163.com","你好,这是一封测试邮件,无需回复。","测试邮件"); System.out.println("发送成功"); } }

6. Md5Utils

/** * 写一个MD5算法,运行结果与MySQL的md5()函数相同 * 将明文密码转成MD5密码 * 123456->e10adc3949ba59abbe56e057f20f883e */ public final class Md5Util { private Md5Util(){} /** * 将明文密码转成MD5密码 */ public static String encodeByMd5(String password) throws Exception{ //Java中MessageDigest类封装了MD5和SHA算法,今天我们只要MD5算法 MessageDigest md5 = MessageDigest.getInstance("MD5"); //调用MD5算法,即返回16个byte类型的值 byte[] byteArray = md5.digest(password.getBytes()); //注意:MessageDigest只能将String转成byte[],接下来的事情,由我们程序员来完成 return byteArrayToHexString(byteArray); } /** * 将byte[]转在16进制字符串 */ private static String byteArrayToHexString(byte[] byteArray) { StringBuffer sb = new StringBuffer(); //遍历 for(byte b : byteArray){//16次 //取出每一个byte类型,进行转换 String hex = byteToHexString(b); //将转换后的值放入StringBuffer中 sb.append(hex); } return sb.toString(); } /** * 将byte转在16进制字符串 */ private static String byteToHexString(byte b) {//-31转成e1,10转成0a,。。。 //将byte类型赋给int类型 int n = b; //如果n是负数 if(n < 0){ //转正数 //-31的16进制数,等价于求225的16进制数 n = 256 + n; } //商(14),数组的下标 int d1 = n / 16; //余(1),数组的下标 int d2 = n % 16; //通过下标取值 return hex[d1] + hex[d2]; } private static String[] hex = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"}; /** * 测试 */ public static void main(String[] args) throws Exception{ String password = "123456"; String passwordMD5 = Md5Util.encodeByMd5(password); System.out.println(password); System.out.println(passwordMD5); } }
最新回复(0)