Web开发中个人String工具类: 提供 toUTF8, toGBK, toHtml, formatDate

本文介绍了一个实用的字符串工具类,提供了多种字符串处理方法,包括HTML转换、编码转换及日期格式化等。这些方法有助于简化Web开发中常见的字符处理任务。

     没事翻了翻以前写的代码,感觉这个比较常用,贴出来一遍日后查询.

 

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * String类型的工具类,用于进行web开发中的字符格式转换。
 * @author 吕健
 * @version 1.0  
 * @since 2008-11-26
 * notes: 
 * 1.提供toHtml()方法,用于将字符串中的特殊字符转换成html代码<br />
 * 2.提供toGBK()方法,用于将'ISO-8859-1'格式编码的字符转换成GBK格式<br />
 * 3.提供toUTF8()方法,用于将'ISO-8859-1'格式编码的字符转换成UTF-8格式
 */
public final class StringUtility {
    private StringUtility() {
    }
    
    /**
     * "ISO-8859-1"格式字符转换成"GBK"
     * @param str "ISO-8859-1"格式字符
     * @return "GBK"格式字符
     */
    public static String toUTF8(String str) {
    	try {
            str = new String(str.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        return str;
    }
    
    /**
     * 格式化显示日期
     * @param date java.util.Date
     * @param format 日期格式,如: yyyy年MM月dd日
     * @return String
     */
    public static String formatDate(Date date, String format) {
    	SimpleDateFormat dateFormat = new SimpleDateFormat();
    	
    	return dateFormat.format(date);
    }
    
    /**
     * "ISO-8859-1"格式字符转换成"GBK"
     * @param str "ISO-8859-1"格式字符
     * @return "UTF-8"格式字符
     */
    public static String toGBK(String str) {
        try {
            str = new String(str.getBytes("ISO-8859-1"), "gb2312");
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        return str;
    }

    /**
     * 将普通文本转换成html文本,避免html显示错误现象
     * @param str String
     * @return String
     */
    public static String toHtml(String str) {
        if(str == null)
            return null;
        StringBuffer sb = new StringBuffer();
        //获取字符串的长度
        int len = str.length();

        //转换特殊字符串
        for(int i = 0; i < len; i++) {
            char c = str.charAt(i);
            switch(c) {
            case ' ':
                sb.append("&nbsp;");
                break;
            case '\n':
                sb.append("<br>");
                break;
            case '\r':
                break;
            case '\'':
                sb.append("&#39;");
                break;
            case '<':
                sb.append("&lt;");
                break;
            case '>':
                sb.append("&gt;");
                break;
            case '&':
                sb.append("&amp;");
                break;
            case '"':
                sb.append("&#34");
                break;
            case '\\':
                sb.append("&#92");
                break;
            default:
                sb.append(c);
            }//end switch
        }//end for

        return sb.toString();
    }

//    public static void main(String[] args) {
//        String test = "<thml>哈哈asdf \" \\ 噢噢 ";
//        System.out.println(test);
//        System.out.println(StringUtility.toHtml(test));
//    }
}
 
### Java 常用工具类汇总 以下是常见的 Java 工具类及其功能描述: #### 字符串处理工具类 `StringUtils` 是 Apache Commons Lang 库中的一个非常强大的字符串操作工具类。它提供了许多用于字符串验证、截取、替换等功能的方法[^1]。 ```java import org.apache.commons.lang3.StringUtils; public class StringUtilsExample { public static void main(String[] args) { System.out.println(StringUtils.isBlank(null)); // true System.out.println(StringUtils.isEmpty("")); // true System.out.println(StringUtils.substringBetween("<html><body>Text</body></html>", "<body>", "</body>")); // Text } } ``` #### 随机生成字符串工具类 可以利用 `RandomStringUtils` 来快速生成随机字符串,适用于密码生成或其他需要随机性的场景[^2]。 ```java import org.apache.commons.lang3.RandomStringUtils; public class RandomStringUtilsExample { public static void main(String[] args) { String randomAlphanumeric = RandomStringUtils.randomAlphanumeric(10); System.out.println(randomAlphanumeric); // 输出长度为10的随机字母数字组合 } } ``` #### 对象比较工具类 `Objects` 类提供了一些静态方法来简化对象的操作,比如判断两个对象是否相等或者计算哈希码[^3]。 ```java import java.util.Objects; public class ObjectsExample { public static void main(String[] args) { Person p1 = new Person("John", 30); Person p2 = new Person("John", 30); boolean isEqual = Objects.equals(p1, p2); System.out.println(isEqual); // 如果重写了equals,则可能输出true } static class Person { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Person)) return false; Person person = (Person) o; return age == person.age && Objects.equals(name, person.name); } } } ``` #### Bean 操作工具类 `BeanUtils` 提供了复制属性的功能,能够方便地在不同类型的 bean 之间传递数据[^4]。 ```java import org.apache.commons.beanutils.BeanUtils; public class BeanUtilsExample { public class Source { private String value; public String getValue() { return value; } public void setValue(String value) { this.value = value; } } public class Target { private String value; public String getValue() { return value; } public void setValue(String value) { this.value = value; } } public void copyProperties() throws Exception { Source source = new Source(); source.setValue("test"); Target target = new Target(); BeanUtils.copyProperties(target, source); System.out.println(target.getValue()); // test } } ``` #### 数组操作工具类 `ArrayUtils` 可以用来执行各种数组操作,如克隆、添加元素、查找下标等[^5]。 ```java import org.apache.commons.lang3.ArrayUtils; public class ArrayUtilsExample { public static void main(String[] args) { Integer[] array = {1, 2, 3}; Integer[] newArray = ArrayUtils.add(array, 4); System.out.println(ArrayUtils.contains(newArray, 4)); // true } } ``` #### BigDecimal 处理工具类 对于高精度数值运算,推荐使用 `BigDecimal` 的扩展工具类来进行更复杂的财务计算。 #### 文件操作工具类 `FileUtils` 和 `IOUtils` 能够帮助开发者轻松完成文件读写以及流管理的任务[^2]。 ```java import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import java.io.File; import java.io.FileInputStream; import java.nio.charset.StandardCharsets; public class FileUtilsExample { public static void readFileContent(File file) throws Exception { String content = FileUtils.readFileToString(file, StandardCharsets.UTF_8); System.out.println(content); } public static void readStreamContent(FileInputStream stream) throws Exception { String content = IOUtils.toString(stream, StandardCharsets.UTF_8); System.out.println(content); } } ``` #### 时间日期工具类 时间日期相关的逻辑可以通过自定义的时间工具类来封装,从而提高代码可维护性和复用率[^3]。 ```java import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class DateUtil { public static LocalDate getLastMonthStartDay(LocalDate date) { return date.minusMonths(1).withDayOfMonth(1); } public static String formatDate(LocalDate date) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); return date.format(formatter); } } ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值