首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

實用 Java 工具方法精選(二):數值轉換、字串分割、資料庫操作與 JSP 輔助函式

     編輯:Java 相關知識

本文整理一組實務上常用的 Java 工具方法,涵蓋浮點數四捨五入轉整數、字串分割、資料庫常用查詢封裝、JSP 輸出輔助等,適合直接納入專案工具類庫。

數值處理工具

銀行家四捨五入 (Round Half to Even)


/** 
 * 浮點數轉整數:採用銀行家演算法 (0.5 進位到最近偶數)
 * 避免傳統四捨五入的統計偏差
 */
public static int cInt(float value) {
    if (value == 0) return 0;
    boolean negative = value < 0;
    float abs = Math.abs(value);
    int intPart = (int) abs;
    float frac = abs - intPart;
    
    int result;
    if (frac > 0.5f || (frac == 0.5f && intPart % 2 != 0)) {
        result = intPart + 1;
    } else {
        result = intPart;
    }
    return negative ? -result : result;
}

/** 浮點數轉長整數 */
public static long cLng(float value) {
    return cInt(value); // 自動拓寬
}

/** 安全字串轉浮點數 */
public static float parseFloatSafe(String s) {
    if (s == null || s.trim().isEmpty()) return 0f;
    try {
        return Float.parseFloat(s.trim());
    } catch (NumberFormatException e) {
        return 0f;
    }
}

字串分割工具


/**
 * 依分隔字串分割(支援多字元分隔符)
 * @return 分割後陣列,空字串回傳長度 0 陣列
 */
public static String[] split(String source, String delimiter) {
    if (source == null || source.isEmpty()) return new String[0];
    if (delimiter == null || delimiter.isEmpty()) return new String[]{source};
    
    List parts = new ArrayList<>();
    int start = 0;
    int idx;
    while ((idx = source.indexOf(delimiter, start)) != -1) {
        parts.add(source.substring(start, idx));
        start = idx + delimiter.length();
    }
    parts.add(source.substring(start));
    return parts.toArray(new String[0]);
}

註:Java 1.4+ 內建 String.split(regex) 已足夠強大,僅在舊版本或需非正則分隔時使用自訂版本。

資料庫操作封裝 (JDBC 輔助)


/** 查詢筆數 */
public static int countRows(Connection conn, String table, String whereClause) 
        throws SQLException {
    String sql = "SELECT COUNT(*) FROM " + table + 
                 (whereClause == null || whereClause.isEmpty() ? "" : " WHERE " + whereClause);
    try (Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery(sql)) {
        return rs.next() ? rs.getInt(1) : 0;
    }
}

/** 查詢非空欄位筆數 */
public static int countNonNull(Connection conn, String table, String column, String whereClause)
        throws SQLException {
    String sql = "SELECT COUNT(*) FROM " + table + " WHERE " + column + " IS NOT NULL" +
                 (whereClause == null || whereClause.isEmpty() ? "" : " AND " + whereClause);
    try (Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery(sql)) {
        return rs.next() ? rs.getInt(1) : 0;
    }
}

/** 查詢單一欄位值 */
public static String lookup(Connection conn, String column, String table, String whereClause)
        throws SQLException {
    String sql = "SELECT " + column + " FROM " + table + " WHERE " + whereClause;
    try (Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery(sql)) {
        return rs.next() ? rs.getString(column) : null;
    }
}

字串修剪工具


/** 移除尾部空白 (右修剪) */
public static String rTrim(String str) {
    if (str == null || str.isEmpty()) return "";
    int len = str.length();
    while (len > 0 && str.charAt(len - 1) == ' ') {
        len--;
    }
    return str.substring(0, len);
}

JSP 專用輔助函式


/** 輸出指定數量空白 (JSP 頁面對齊用) */
public static void printSpaces(JspWriter out, int count) throws IOException {
    for (int i = 0; i < count; i++) out.print(' ');
}

/** 寫入檔案 (JSP 內部產生靜態檔案用) */
public static void writeFile(String content, String filePath) {
    try (PrintWriter pw = new PrintWriter(new FileOutputStream(filePath))) {
        pw.println(content);
    } catch (IOException e) {
        log.error("寫入檔案失敗: " + filePath, e);
    }
}

位元組操作工具


/** 字串 OR 運算(逐字元 '0'/'1' 邏輯或) */
public static String charOr(String a, String b) {
    if (a == null || a.isEmpty()) return b == null ? "" : b;
    if (b == null || b.isEmpty()) return a;
    
    int maxLen = Math.max(a.length(), b.length());
    StringBuilder sb = new StringBuilder(maxLen);
    for (int i = 0; i < maxLen; i++) {
        char ca = i < a.length() ? a.charAt(i) : '0';
        char cb = i < b.length() ? b.charAt(i) : '0';
        sb.append((ca == '1' || cb == '1') ? '1' : '0');
    }
    return sb.toString();
}

資料傳輸物件 (DTO) 範例


public class RsybName {
    public int pos = -1;
    public String name = "";
    public String host = "";
    public String home1 = "";
    public String home2 = "";
    public String home3 = "";
}

public class SybInf {
    public String regName = "";
    public String gSyb = "";
    public String rSyb = "";
}

這些工具方法經過實戰驗證,建議整理為 com.util 套件下的 NumberUtils、StringUtils、DbUtils、JspUtils 等分類類別,並加入完整 JavaDoc 與單元測試。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved