日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

常用工具类的积累

發布時間:2023/12/20 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 常用工具类的积累 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1.將XML轉換為Map集合(下面的代碼中request返回的就是xml)

public static Map<String, String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException {Map<String, String> map = new HashMap<String, String>();SAXReader reader = new SAXReader();InputStream input = request.getInputStream();Document doc = reader.read(input);Element root = doc.getRootElement();List<Element> list = root.elements();for (Element e : list) {map.put(e.getName(), e.getText());}input.close();return map;}

以上代碼使用到的jar包有:

2.將pojo類轉換為XML格式的數據

student類:(pojo類)

package com.huihui.test3;public class Student {private String name;private int age;private String sex;private String birth;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public String getBirth() {return birth;}public void setBirth(String birth) {this.birth = birth;}}

School類:(pojo類)

package com.huihui.test3;public class School {private String schoolName;private Student student;public String getSchoolName() {return schoolName;}public void setSchoolName(String schoolName) {this.schoolName = schoolName;}public Student getStudent() {return student;}public void setStudent(Student student) {this.student = student;}}

測試類:

package com.huihui.test3;import com.thoughtworks.xstream.XStream;public class Test {public static void main(String[] args) {Student student = new Student();student.setName("張耀暉");student.setAge(24);student.setSex("男");student.setBirth("1992-11-03");School school = new School();school.setSchoolName("南華大學");school.setStudent(student);XStream xstream = new XStream();xstream.alias("xml", school.getClass());String xmlstr = xstream.toXML(school);System.out.println(xmlstr);}}

以上代碼所用到的jar包:

運行結果截圖:

3.使用Get或者Post請求的方式請求一個URL(請求url后會返回json數據才可以)

Get請求方式:

public static JSONObject doGetStr(String url) {DefaultHttpClient httpClient = new DefaultHttpClient();HttpGet httpGet = new HttpGet(url);JSONObject jsonObject = null;try {HttpResponse response = httpClient.execute(httpGet);// 接收請求后的返回的結果HttpEntity entity = response.getEntity();if (entity != null) {String result = EntityUtils.toString(entity, "UTF-8");jsonObject = JSONObject.fromObject(result);}} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return jsonObject;}

Post請求方式:

public static JSONObject doPostStr(String url, String outStr) {DefaultHttpClient httpClient = new DefaultHttpClient();HttpPost httpPost = new HttpPost(url);JSONObject jsonObject = null;try {httpPost.setEntity(new StringEntity(outStr, "UTF-8"));HttpResponse response = httpClient.execute(httpPost);String result = EntityUtils.toString(response.getEntity(), "UTF-8");jsonObject = JSONObject.fromObject(result);} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return jsonObject;}

以上代碼使用的jar包:

4.文件上傳

public static String upload(String filePath, String accessToken, String type)throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {File file = new File(filePath);if (!file.exists() || !file.isFile()) {throw new IOException("文件不存在");}String url = UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);URL urlObj = new URL(url);// 連接HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();con.setRequestMethod("POST");con.setDoInput(true);con.setDoOutput(true);con.setUseCaches(false);// 設置請求頭信息con.setRequestProperty("Connection", "Keep-Alive");con.setRequestProperty("Charset", "UTF-8");// 設置邊界String BOUNDARY = "----------" + System.currentTimeMillis();con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);StringBuilder sb = new StringBuilder();sb.append("--");sb.append(BOUNDARY);sb.append("\r\n");sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");sb.append("Content-Type:application/octet-stream\r\n\r\n");byte[] head = sb.toString().getBytes("utf-8");// 獲得輸出流OutputStream out = new DataOutputStream(con.getOutputStream());// 輸出表頭out.write(head); // 文件正文部分// 把文件已流文件的方式 推入到url中DataInputStream in = new DataInputStream(new FileInputStream(file));int bytes = 0;byte[] bufferOut = new byte[1024];while ((bytes = in.read(bufferOut)) != -1) {out.write(bufferOut, 0, bytes);}in.close();// 結尾部分byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定義最后數據分隔線out.write(foot);out.flush();out.close();StringBuffer buffer = new StringBuffer();BufferedReader reader = null;String result = null;try {// 定義BufferedReader輸入流來讀取URL的響應reader = new BufferedReader(new InputStreamReader(con.getInputStream()));String line = null;while ((line = reader.readLine()) != null) {buffer.append(line);}if (result == null) {result = buffer.toString();}} catch (IOException e) {e.printStackTrace();} finally {if (reader != null) {reader.close();}}JSONObject jsonObj = JSONObject.fromObject(result);System.out.println(jsonObj);String typeName = "media_id";if ("thumb".equals(type)) {typeName = type + "_media_id";}String mediaId = jsonObj.getString(typeName);return mediaId;}

5.SHA1加密

//sha1加密public static String getSha1(String str){if(str==null||str.length()==0){return null;}char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};try {MessageDigest mdTemp = MessageDigest.getInstance("SHA1");mdTemp.update(str.getBytes("UTF-8"));byte[] md = mdTemp.digest();int j = md.length;char buf[] = new char[j*2];int k = 0;for (int i = 0; i < j; i++) {byte byte0 = md[i];buf[k++] = hexDigits[byte0 >>> 4 & 0xf];buf[k++] = hexDigits[byte0 & 0xf];}return new String(buf);} catch (Exception e) {return null;}}

6.MD5加密工具類:

package com.huihui.util;import java.security.MessageDigest;/*** MD5加密工具類* @author Administrator**/ public class Md5Util {public final static String MD5(String s){char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; try {byte[] strTemp = s.getBytes();MessageDigest mdTemp = MessageDigest.getInstance("MD5");mdTemp.update(strTemp);byte[] md = mdTemp.digest();int j = md.length;char str[] = new char[j*2];int k = 0;for (int i = 0; i < j; i++) {byte byte0 = md[i];str[k++] = hexDigits[byte0>>>4&0xf];str[k++] = hexDigits[byte0 & 0xf];}return new String(str);} catch (Exception e) {return null;}}public static void main(String[] args) {System.out.println(Md5Util.MD5("b"));} }

7.SQL工具類:

package com.huihui.util;import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.Properties;/*** 這是一個操作數據庫的工具類* * @author Administrator* */ public class SqlHelper {private static String DBDRIVER;private static String DBURL;private static String DBUSER;private static String DBPASS;// 定義需要的變量private static Connection conn = null;private static PreparedStatement pstmt = null;private static ResultSet rs = null;public static Connection getConn() {return conn;}public static PreparedStatement getPstmt() {return pstmt;}public static ResultSet getRs() {return rs;}// 加載驅動,只需要加載一次static {FileInputStream fis = null;try {// 從dbinfo.properties文件中讀取配置信息Properties pp = new Properties();fis = new FileInputStream("E:\\myeclipse10code\\UserLoginUp\\dbinfo.properties");pp.load(fis);DBDRIVER = pp.getProperty("driver");DBURL = pp.getProperty("url");DBUSER = pp.getProperty("user");DBPASS = pp.getProperty("pass");Class.forName(DBDRIVER);} catch (Exception e) {e.printStackTrace();} finally {try {fis.close();} catch (IOException e) {e.printStackTrace();}fis = null;}}// 得到連接public static Connection getConnection() {try {conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);} catch (SQLException e) {e.printStackTrace();}return conn;}// 關閉資源public static void close(ResultSet rs, PreparedStatement pstmt,Connection conn) {if (rs != null) {try {rs.close();} catch (Exception e) {e.printStackTrace();} finally {rs = null;}}if (pstmt != null) {try {pstmt.close();} catch (Exception e) {e.printStackTrace();} finally {pstmt = null;}}if (conn != null) {try {conn.close();} catch (Exception e) {e.printStackTrace();} finally {conn = null;}}}// 先寫一個update/delete/insert// sql格式: update 表名 set 字段名=? where 字段=?public static void executeUpdate1(String sql, String[] parameters) {try {conn = getConnection();pstmt = conn.prepareStatement(sql);// 給?賦值if (parameters != null) {for (int i = 0; i < parameters.length; i++) {pstmt.setString(i + 1, parameters[i]);}}// 執行pstmt.executeUpdate();} catch (Exception e) {e.printStackTrace();throw new RuntimeException(e.getMessage());} finally {close(rs, pstmt, conn);}}// 如果有多個update/delete/insert語句【需要考慮事務】public static void executeUpdate2(String[] sqls, String[][] parameters) {try {conn = getConnection();// 因為這時用戶傳入的可能是多個sql語句conn.setAutoCommit(false);if (sqls != null) {for (int i = 0; i < parameters.length; i++) {pstmt = conn.prepareStatement(sqls[i]);if (parameters[i] != null) {for (int j = 0; j < parameters[i].length; j++) {pstmt.setString(j + 1, parameters[i][j]);}}pstmt.executeUpdate();}}conn.commit();} catch (Exception e) {// 回滾try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}e.printStackTrace();throw new RuntimeException(e.getMessage());} finally {close(rs, pstmt, conn);}}// 統一的selectpublic static ResultSet executeQuery(String sql, String[] parameters) {try {conn = getConnection();pstmt = conn.prepareStatement(sql);if (parameters != null) {for (int i = 0; i < parameters.length; i++) {pstmt.setString(i + 1, parameters[i]);}}System.out.println(pstmt);rs = pstmt.executeQuery();} catch (Exception e) {e.printStackTrace();throw new RuntimeException(e.getMessage());} finally {// 如果這里關閉了資源,就沒法使用ResultSet了,也就沒法return了// close(rs, pstmt, conn);}return rs;}//修改后的統一的select (ResultSet-->ArrayList)public static ArrayList executeQuery1(String sql,String[] parameters){ArrayList list = new ArrayList();try {conn = getConnection();pstmt = conn.prepareStatement(sql);if(parameters!=null){for (int i = 0; i < parameters.length; i++) {pstmt.setString(i+1, parameters[i]);}}System.out.println(pstmt);rs = pstmt.executeQuery();ResultSetMetaData rsmd = rs.getMetaData();int column = rsmd.getColumnCount();//這里可以得到你查詢語句返回的總的列數while (rs.next()) {Object[] ob = new Object[column];//對象數組,表示一行數據for (int i = 0; i < column; i++) {ob[i] = rs.getObject(i+1);}list.add(ob);}return list;} catch (Exception e) {e.printStackTrace();throw new RuntimeException(e.getMessage());} finally{//關閉資源close(rs, pstmt, conn);}}}

8.Hibernate工具類

package com.huihui.util;import java.util.List;import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration;final public class HibernateUtil {private static SessionFactory sessionFactory = null;// 使用線程局部模式private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();private HibernateUtil() {}static {sessionFactory = new Configuration().configure().buildSessionFactory();}// 獲取一個全新的Sessionpublic static Session openSession() {return sessionFactory.openSession();}// 獲取和線程關聯的Sessionpublic static Session getCurrentSession() {Session session = threadLocal.get();// 判斷是否得到了if (session == null) {session = sessionFactory.openSession();// 把session對象設置到threadLocal中去,相當于該Session已經和線程綁定threadLocal.set(session);}return session;}//統一的修改和刪除public static void executeUpdate(String hql,String[] parameters){Session session = null;Transaction transaction = null;try {session = openSession();transaction = session.beginTransaction();Query query = session.createQuery(hql);if(parameters!=null&&parameters.length>0){for (int i = 0; i < parameters.length; i++) {query.setString(i, parameters[i]);}}query.executeUpdate();transaction.commit();} catch (Exception e) {if(transaction!=null){transaction.rollback();}e.printStackTrace();throw new RuntimeException(e.getMessage());} finally{if(session!=null&&session.isOpen()){session.close();}}}//統一的添加方法public static void save(Object obj){Session session = null;Transaction transaction = null;try {session = openSession();transaction = session.beginTransaction();session.save(obj);transaction.commit();} catch (Exception e) {if(transaction!=null){transaction.rollback();}e.printStackTrace();throw new RuntimeException(e.getMessage());} finally{if(session!=null&&session.isOpen()){session.close();}}}//提供返回只有一個結果的查詢(一個結果)public static Object executeQueryForOne(String hql,String[] parameters){Object o = null;Session session = null;try {session = openSession();Query query = session.createQuery(hql);if(parameters!=null&&parameters.length>0){for (int i = 0; i < parameters.length; i++) {query.setString(i, parameters[i]);}}o = query.uniqueResult();} catch (Exception e) {e.printStackTrace();throw new RuntimeException(e.getMessage());} finally{if(session!=null&&session.isOpen()){session.close();}}return o;}// 提供一個統一的查詢方法(帶分頁)public static List executeQueryByPage(String hql, String[] parameters,int pageSize, int pageNow) {List list = null;Session session = null;try {session = openSession();Query query = session.createQuery(hql);if(parameters!=null&&parameters.length>0){for (int i = 0; i < parameters.length; i++) {query.setString(i, parameters[i]);}}query.setFirstResult((pageNow-1)*pageSize).setMaxResults(pageSize);list = query.list();} catch (Exception e) {e.printStackTrace();throw new RuntimeException(e.getMessage());} finally{if(session!=null&&session.isOpen()){session.close();}}return list;}// 提供統一的查詢方法.hql形式:from 類 where 條件=?...(多個結果)public static List executeQuery(String hql, String[] parameters) {Session session = null;Transaction transaction = null;List list = null;try {session = getCurrentSession();transaction = session.beginTransaction();Query query = session.createQuery(hql);if (parameters != null && parameters.length > 0) {for (int i = 0; i < parameters.length; i++) {query.setString(i, parameters[i]);}}list = query.list();transaction.commit();} catch (Exception e) {if (transaction != null) {transaction.rollback();}e.printStackTrace();throw new RuntimeException(e.getMessage());} finally {if (session != null && session.isOpen()) {session.close();}session = null;}return list;}}

9.圖片驗證碼生成器

基礎的驗證碼包括了數字、字母、甚至可能有漢字。下面我給出一個簡單的工具類

package com.huihui.test5;import java.awt.Color;import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Date; import java.util.Random;import javax.imageio.ImageIO;/*** 驗證碼生成器*/ public class ValidateCode {// 圖片的寬度。private int width = 160;// 圖片的高度。private int height = 40;// 驗證碼字符個數private int codeCount = 5;// 驗證碼干擾線數private int lineCount = 150;// 驗證碼private static String code = null;// 驗證碼圖片Bufferprivate BufferedImage buffImg = null;private char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R','S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };public ValidateCode() {this.createCode();}/*** * @param width* 圖片寬* @param height* 圖片高*/public ValidateCode(int width, int height) {this.width = width;this.height = height;this.createCode();}/*** * @param width* 圖片寬* @param height* 圖片高* @param codeCount* 字符個數* @param lineCount* 干擾線條數*/public ValidateCode(int width, int height, int codeCount, int lineCount) {this.width = width;this.height = height;this.codeCount = codeCount;this.lineCount = lineCount;this.createCode();}public void createCode() {int x = 0, fontHeight = 0, codeY = 0;int red = 0, green = 0, blue = 0;x = width / (codeCount + 1);// 每個字符的寬度fontHeight = height - 2;// 字體的高度codeY = height - 3;// 圖像bufferbuffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics2D g = buffImg.createGraphics();// 生成隨機數Random random = new Random();// 將圖像填充為白色g.setColor(Color.WHITE);g.fillRect(0, 0, width, height);// 創建字體ImgFontByte imgFont = new ImgFontByte();Font font = imgFont.getFont(fontHeight);g.setFont(font);for (int i = 0; i < lineCount; i++) {int xs = random.nextInt(width);int ys = random.nextInt(height);int xe = xs + random.nextInt(width / 8);int ye = ys + random.nextInt(height / 8);red = random.nextInt(255);green = random.nextInt(255);blue = random.nextInt(255);g.setColor(new Color(red, green, blue));g.drawLine(xs, ys, xe, ye);}// randomCode記錄隨機產生的驗證碼StringBuffer randomCode = new StringBuffer();// 隨機產生codeCount個字符的驗證碼。for (int i = 0; i < codeCount; i++) {String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);// 產生隨機的顏色值,讓輸出的每個字符的顏色值都將不同。red = random.nextInt(255);green = random.nextInt(255);blue = random.nextInt(255);g.setColor(new Color(red, green, blue));g.drawString(strRand, (i + 1) * x, codeY);// 將產生的四個隨機數組合在一起。randomCode.append(strRand);}// 將四位數字的驗證碼保存到Session中。code = randomCode.toString();}public void write(String path,String fileName) throws IOException {File folder = new File(path);if(!folder.exists()){folder.mkdirs();}OutputStream sos = new FileOutputStream(path+fileName);this.write(sos);}public void write(OutputStream sos) throws IOException {ImageIO.write(buffImg, "png", sos);sos.close();}public BufferedImage getBuffImg() {return buffImg;}public String getCode() {return code;}public static void main(String[] args) { ValidateCode vCode = new ValidateCode(120,40,5,50); try { String path="C:\\Users\\Administrator\\Desktop\\"; System.out.println(vCode.getCode()+" >"+path); vCode.write(path,new Date().getTime()+".png"); } catch (IOException e) { e.printStackTrace();} }}

下面這個類主要是用作字體的設置:

package com.huihui.test5;import java.awt.Font; import java.io.ByteArrayInputStream;public class ImgFontByte {public Font getFont(int fontHeight){ try { Font baseFont = Font.createFont(Font.ITALIC, new ByteArrayInputStream(hex2byte(getFontByteStr()))); return baseFont.deriveFont(Font.PLAIN, fontHeight); } catch (Exception e) { return new Font("Consola",Font.PLAIN, fontHeight); } } private byte[] hex2byte(String str) { if (str == null) return null; str = str.trim(); int len = str.length(); if (len == 0 || len % 2 == 1) return null; byte[] b = new byte[len / 2]; try { for (int i = 0; i < str.length(); i += 2) { b[i/2] = (byte) Integer.decode("0x" + str.substring(i, i + 2)).intValue(); } return b; } catch (Exception e) { return null; } } /** * ttf字體文件的十六進制字符串 * @return */ private String getFontByteStr(){ return null; } }

總結

以上是生活随笔為你收集整理的常用工具类的积累的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。