org.apache.commons.lang.StringUtil 常用方法使用例子

本文介绍了Java中使用Apache Commons Lang库进行字符串处理的各种实用方法,包括空字符串检查、清除空白字符、字符串缩写等。

1.空字符串检查
使用函数: StringUtils.isBlank(testString)
函数介绍: 当testString为空,长度为零或者仅由空白字符(whitespace)组成时,返回True;否则返回False
例程:

  1. String test = "";   
  2. String test2 = "\n\n\t";   
  3. String test3 = null;   
  4. String test4 = "Test";    
  5. System.out.println( "test blank? " + StringUtils.isBlank( test ) );   
  6. System.out.println( "test2 blank? " + StringUtils.isBlank( test2 ) );   
  7. System.out.println( "test3 blank? " + StringUtils.isBlank( test3 ) );   
  8. System.out.println( "test4 blank? " + StringUtils.isBlank( test4 ) );  

String test = ""; String test2 = "\n\n\t"; String test3 = null; String test4 = "Test"; System.out.println( "test blank? " + StringUtils.isBlank( test ) ); System.out.println( "test2 blank? " + StringUtils.isBlank( test2 ) ); System.out.println( "test3 blank? " + StringUtils.isBlank( test3 ) ); System.out.println( "test4 blank? " + StringUtils.isBlank( test4 ) );
输出如下:
test blank? true
test2 blank? true
test3 blank? true
test4 blank? False
函数StringUtils.isNotBlank(testString)的功能与StringUtils.isBlank(testString)相反.

2.清除空白字符
使用函数: StringUtils.trimToNull(testString)
函数介绍:清除掉testString首尾的空白字符,如果仅testString全由空白字符
(whitespace)组成则返回null
例程:

  1. String test1 = "\t";   
  2. String test2 = " A Test ";   
  3. String test3 = null;   
  4.   
  5. System.out.println( "test1 trimToNull: " + StringUtils.trimToNull( test1 ) );   
  6. System.out.println( "test2 trimToNull: " + StringUtils.trimToNull( test2 ) );   
  7. System.out.println( "test3 trimToNull: " + StringUtils.trimToNull( test3 ) );  

String test1 = "\t"; String test2 = " A Test "; String test3 = null; System.out.println( "test1 trimToNull: " + StringUtils.trimToNull( test1 ) ); System.out.println( "test2 trimToNull: " + StringUtils.trimToNull( test2 ) ); System.out.println( "test3 trimToNull: " + StringUtils.trimToNull( test3 ) );
输出如下:
test1 trimToNull: null
test2 trimToNull: A Test
test3 trimToNull: null

注意:函数StringUtils.trim(testString)与
StringUtils.trimToNull(testString)功能类似,但testString由空白字符
(whitespace)组成时返回零长度字符串。

3.取得字符串的缩写
使用函数: StringUtils.abbreviate(testString,width)和StringUtils.abbreviate(testString,offset,width)
函数介绍:在给定的width内取得testString的缩写,当testString的长度小于width则返回原字符串.
例程:

  1. String test = "This is a test of the abbreviation.";   
  2. String test2 = "Test";   
  3.   
  4. System.out.println( StringUtils.abbreviate( test, 15 ) );   
  5. System.out.println( StringUtils.abbreviate( test, 5,15 ) );   
  6. System.out.println( StringUtils.abbreviate( test2, 10 ) );  

String test = "This is a test of the abbreviation."; String test2 = "Test"; System.out.println( StringUtils.abbreviate( test, 15 ) ); System.out.println( StringUtils.abbreviate( test, 5,15 ) ); System.out.println( StringUtils.abbreviate( test2, 10 ) );
输出如下:
This is a te...
...is a test...
Test

4.劈分字符串
使用函数: StringUtils.split(testString,splitChars,arrayLength)
函数介绍:splitChars中可以包含一系列的字符串来劈分testString,并可以设定得
到数组的长度.注意设定长度arrayLength和劈分字符串间有抵触关系,建议一般情况下
不要设定长度.
例程:

  1. String input = "A b,c.d|e";   
  2. String input2 = "Pharmacy, basketball funky";   
  3.   
  4. String[] array1 = StringUtils.split( input, " ,.|");   
  5. String[] array2 = StringUtils.split( input2, " ,"2 );   
  6.   
  7. System.out.println( ArrayUtils.toString( array1 ) );   
  8. System.out.println( ArrayUtils.toString( array2 ) );  

String input = "A b,c.d|e"; String input2 = "Pharmacy, basketball funky"; String[] array1 = StringUtils.split( input, " ,.|"); String[] array2 = StringUtils.split( input2, " ,", 2 ); System.out.println( ArrayUtils.toString( array1 ) ); System.out.println( ArrayUtils.toString( array2 ) );
输出如下:
{A,b,c,d,e}
{Pharmacy,basketball funky}

5.查找嵌套字符串
使用函数:StringUtils.substringBetween(testString,header,tail)
函数介绍:在testString中取得header和tail之间的字符串。不存在则返回空
例程:

  1. String htmlContent = "ABC1234ABC4567";   
  2. System.out.println(StringUtils.substringBetween(htmlContent, "1234""4567"));   
  3. System.out.println(StringUtils.substringBetween(htmlContent, "12345""4567"));  

String htmlContent = "ABC1234ABC4567"; System.out.println(StringUtils.substringBetween(htmlContent, "1234", "4567")); System.out.println(StringUtils.substringBetween(htmlContent, "12345", "4567"));
输出如下:
    ABC
    null


6.去除尾部换行符
使用函数:StringUtils.chomp(testString)
函数介绍:去除testString尾部的换行符
例程:

  1. String input = "Hello\n";   
  2. System.out.println( StringUtils.chomp( input ));   
  3. String input2 = "Another test\r\n";   
  4. System.out.println( StringUtils.chomp( input2 ));  

String input = "Hello\n"; System.out.println( StringUtils.chomp( input )); String input2 = "Another test\r\n"; System.out.println( StringUtils.chomp( input2 ));
输出如下:
    Hello
    Another test


7.重复字符串
使用函数:StringUtils.repeat(repeatString,count)
函数介绍:得到将repeatString重复count次后的字符串
例程:

  1. System.out.println( StringUtils.repeat( "*"10));   
  2. System.out.println( StringUtils.repeat( "China "5));  

System.out.println( StringUtils.repeat( "*", 10)); System.out.println( StringUtils.repeat( "China ", 5));
输出如下:
    **********
    China China China China China

其他函数:StringUtils.center( testString, count,repeatString );
函数介绍:把testString插入将repeatString重复多次后的字符串中间,得到字符串
的总长为count
例程:

  1. System.out.println( StringUtils.center( "China"11,"*"));  

System.out.println( StringUtils.center( "China", 11,"*"));
输出如下:
    ***China***


8.颠倒字符串
使用函数:StringUtils.reverse(testString)
函数介绍:得到testString中字符颠倒后的字符串
例程:

  1. System.out.println( StringUtils.reverse("ABCDE"));  

System.out.println( StringUtils.reverse("ABCDE"));
输出如下:
    EDCBA

9.判断字符串内容的类型
函数介绍:
StringUtils.isNumeric( testString ) :如果testString全由数字组成返回True
StringUtils.isAlpha( testString ) :如果testString全由字母组成返回True
StringUtils.isAlphanumeric( testString ) :如果testString全由数字或数字组
成返回True
StringUtils.isAlphaspace( testString ) :如果testString全由字母或空格组
成返回True

例程:

  1. String state = "Virginia";   
  2. System.out.println( "Is state number? " + StringUtils.isNumeric(state ) );   
  3. System.out.println( "Is state alpha? " + StringUtils.isAlpha( state ));   
  4. System.out.println( "Is state alphanumeric? " +StringUtils.isAlphanumeric( state ) );   
  5. System.out.println( "Is state alphaspace? " + StringUtils.isAlphaSpace( state ) );  

String state = "Virginia"; System.out.println( "Is state number? " + StringUtils.isNumeric(state ) ); System.out.println( "Is state alpha? " + StringUtils.isAlpha( state )); System.out.println( "Is state alphanumeric? " +StringUtils.isAlphanumeric( state ) ); System.out.println( "Is state alphaspace? " + StringUtils.isAlphaSpace( state ) );
输出如下:
    Is state number? false
    Is state alpha? true
    Is state alphanumeric? true
    Is state alphaspace? true

10.取得某字符串在另一字符串中出现的次数
使用函数:StringUtils.countMatches(testString,seqString)
函数介绍:取得seqString在testString中出现的次数,未发现则返回零
例程:

  1. System.out.println(StringUtils.countMatches( "Chinese People""e"));  

System.out.println(StringUtils.countMatches( "Chinese People", "e"));
输出:
    4

11.部分截取字符串
使用函数:
StringUtils.substringBetween(testString,fromString,toString ):取得两字符
之间的字符串
StringUtils.substringAfter( ):取得指定字符串后的字符串
StringUtils.substringBefore( ):取得指定字符串之前的字符串
StringUtils.substringBeforeLast( ):取得最后一个指定字符串之前的字符串
StringUtils.substringAfterLast( ):取得最后一个指定字符串之后的字符串

函数介绍:上面应该都讲明白了吧。
例程:

  1. String formatted = " 25 * (30,40) [50,60] | 30";   
  2. System.out.print("N0: " + StringUtils.substringBeforeLast( formatted, "*" ) );   
  3. System.out.print(", N1: " + StringUtils.substringBetween( formatted, "(""," ) );   
  4. System.out.print(", N2: " + StringUtils.substringBetween( formatted, ","")" ) );   
  5. System.out.print(", N3: " + StringUtils.substringBetween( formatted, "[""," ) );   
  6. System.out.print(", N4: " + StringUtils.substringBetween( formatted, ",""]" ) );   
  7. System.out.print(", N5: " + StringUtils.substringAfterLast( formatted, "|" ) );  

String formatted = " 25 * (30,40) [50,60] | 30"; System.out.print("N0: " + StringUtils.substringBeforeLast( formatted, "*" ) ); System.out.print(", N1: " + StringUtils.substringBetween( formatted, "(", "," ) ); System.out.print(", N2: " + StringUtils.substringBetween( formatted, ",", ")" ) ); System.out.print(", N3: " + StringUtils.substringBetween( formatted, "[", "," ) ); System.out.print(", N4: " + StringUtils.substringBetween( formatted, ",", "]" ) ); System.out.print(", N5: " + StringUtils.substringAfterLast( formatted, "|" ) );
输出如下:
    N0: 25 , N1: 30, N2: 40, N3: 50, N4: 40) [50,60, N5: 30

<think>我们正在讨论ApacheCommonsLang库中的DateFormatUtils类。根据引用[1]和[2]的上下文,我们知道org.apache.commons.langcommons-lang包的正确基础包名(注意引用[1]中特别指出不是org.apache.commons.lang.xwork)。引用[3]提到Lang模块提供了一些基础类库的扩展,其中包括时间相关的工具类,因此DateFormatUtils应该在这个包下。用户询问的是org.apache.commons.lang.time.DateFormatUtils的使用方法。首先,我们需要确认这个类的存在。在ApacheCommonsLang的文档中,确实有一个DateFormatUtils类,它位于org.apache.commons.lang.time包下。这个类提供了格式化日期和时间的方法,特别是不需要显式创建SimpleDateFormat实例(因此是线程安全的)。接下来,我将介绍DateFormatUtils的一些常用方法:1.**format(Datedate,Stringpattern)**:使用指定的模式格式化日期。2.**format(Calendarcalendar,Stringpattern)**:使用指定的模式格式化日历对象。3.**format(longmillis,Stringpattern)**:使用指定的模式格式化从1970-01-0100:00:00UTC开始的毫秒数。4.**formatUTC(Datedate,Stringpattern)**:使用UTC时区和指定的模式格式化日期。5.**formatUTC(longmillis,Stringpattern)**:使用UTC时区和指定的模式格式化毫秒数。这些方法都是静态的,可以直接通过类名调用。使用示例:```javaimportjava.util.Date;importorg.apache.commons.lang.time.DateFormatUtils;publicclassDateFormatExample{publicstaticvoidmain(String[]args){Datenow=newDate();//格式化为yyyy-MM-ddHH:mm:ssStringformattedDateTime=DateFormatUtils.format(now,"yyyy-MM-ddHH:mm:ss");System.out.println("当前时间:"+formattedDateTime);//使用UTC时区格式化StringutcDateTime=DateFormatUtils.formatUTC(now,"yyyy-MM-ddHH:mm:ss");System.out.println("当前时间(UTC):"+utcDateTime);}}```注意:模式字符串的格式与Java标准库中的SimpleDateFormat相同。另外,需要确保项目中已经正确引入了commons-lang库。如果使用Maven,可以在pom.xml中添加依赖(请根据实际需要选择版本,这里以2.6为例,但请注意,较新的项目可能使用3.x版本,包名改为org.apache.commons.lang3):```xml<dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency>```如果是使用较新的CommonsLang3.x,则包名变为org.apache.commons.lang3,并且DateFormatUtils类在org.apache.commons.lang3.time包下。因此,如果用户使用的是3.x版本,则导入语句应为:```javaimportorg.apache.commons.lang3.time.DateFormatUtils;```Maven依赖为:```xml<dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.12.0</version><!--使用最新版本--></dependency>```因此,在回答中需要提醒用户注意版本差异。最后,我们还可以提供一些模式字符串的常见用法,例如:-"yyyy-MM-dd":年-月-日-"HH:mm:ss":时:分:秒(24小时制)-"yyyy-MM-dd'T'HH:mm:ssZ":带时区的格式,如2022-01-01T12:00:00+0800总结:DateFormatUtils是一个方便的工具类,用于安全地格式化日期和时间,避免了SimpleDateFormat的线程安全问题。§§相关问题§§1.DateFormatUtils与Java标准库中的SimpleDateFormat有什么区别?2.如何在多线程环境下安全地使用日期格式化?3.CommonsLang库中还有哪些与时间处理相关的工具类?4.如何将字符串解析为日期对象(使用CommonsLang)?</think>### 使用 `org.apache.commons.lang.time.DateFormatUtils` 的方法 `DateFormatUtils` 是 Apache Commons Lang 库中处理日期格式化的工具类,提供线程安全的日期格式化方法(无需创建 `SimpleDateFormat` 实例)。以下是核心用法: #### 1. **基础格式化** ```java import org.apache.commons.lang.time.DateFormatUtils; import java.util.Date; // 格式化为默认模式 String dateStr = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"); System.out.println(dateStr); // 输出: 2023-08-15 14:30:45 // 使用预定义模式(ISO8601标准) String isoDate = DateFormatUtils.ISO_DATETIME_FORMAT.format(new Date()); System.out.println(isoDate); // 输出: 2023-08-15T14:30:45 ``` #### 2. **指定时区格式化** ```java import java.util.TimeZone; // UTC时区格式化 String utcDate = DateFormatUtils.format( new Date(), "yyyy-MM-dd HH:mm:ss", TimeZone.getTimeZone("UTC") ); System.out.println(utcDate); // 输出UTC时间,如: 2023-08-15 06:30:45 ``` #### 3. **日历对象格式化** ```java import java.util.Calendar; Calendar calendar = Calendar.getInstance(); String calStr = DateFormatUtils.format(calendar, "yyyy年MM月dd日"); System.out.println(calStr); // 输出: 2023年08月15日 ``` #### 4. **毫秒时间戳格式化** ```java long timestamp = System.currentTimeMillis(); String timeStr = DateFormatUtils.format(timestamp, "HH:mm:ss.SSS"); System.out.println(timeStr); // 输出: 14:30:45.123 ``` ### 注意事项 1. **依赖配置**(Maven): ```xml <!-- Commons Lang 2.x --> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> ``` > ⚠️ 若使用 Lang 3.x,包名改为 `org.apache.commons.lang3.time.DateFormatUtils`。 2. **模式语法**: 与 `SimpleDateFormat` 兼容,例如: - `yyyy`:4位年份 - `MM`:月份(01-12) - `dd`:日期(01-31) - `HH`:24小时制小时 3. **线程安全**: 所有方法均为静态且线程安全[^1][^3]。 ### 完整示例 ```java import org.apache.commons.lang.time.DateFormatUtils; import java.util.*; public class DateExample { public static void main(String[] args) { // 格式化当前日期 String date1 = DateFormatUtils.format(new Date(), "yyyy-MM-dd"); System.out.println("当前日期: " + date1); // 指定时区(GMT+8) String date2 = DateFormatUtils.format( new Date(), "yyyy-MM-dd HH:mm:ss z", TimeZone.getTimeZone("GMT+8") ); System.out.println("北京时间: " + date2); // 输出: 2023-08-15 14:30:45 GMT+08:00 } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值