免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費(fèi)電子書等14項(xiàng)超值服

開通VIP
妙用Commons良藥
妙用commons良藥<一>
這一篇文章主要是講Commons IO的一些內(nèi)容.
Commons IO提供了org.apache.commons.io.CopyUtils類來(lái)將某個(gè)InputStream,Reader,byte[]數(shù)據(jù)或字符串的內(nèi)容拷貝到OutputStream或Writer.
Java代碼 
Writer writer = new FileWriter( "test.dat" );
InputStream inputStream =
getClass( ).getResourceAsStream("./test.resource");
CopyUtils.copy( inputStream, writer );
writer.close( );
inputStream.close( );
如果需要把信息從Reader或InputStream拷貝到字符串中,請(qǐng)使用IOUtils.toString()方法.
Java代碼 
InputStream inStream = url.openStream( );
String contents = IOUtils.toString( inStream );
通過(guò)org.apache.commons.io.IOUtils,你可以很好地關(guān)閉某個(gè)InputStream,OutputStream,Reader或Writer,而不必?fù)?dān)心null或IOException.
Java代碼 
try {
File file = new File( "test.dat" );
reader = new FileReader( file );
result = CopyUtils.toString( reader );
} catch( IOException ioe ) {
System.out.println( "Unable to copy file test.dat to a String." );
} finally {
IOUtils.closeQuietly( reader );
}
使用FileUtils.byteCountToDisplaySize()生成一個(gè)字符串,該字符串含有有一個(gè)近似的比較好理解的文件的相對(duì)大小的值.
Java代碼 
File file = new File("project.xml");
long bytes = file.length( );
String display = FileUtils.byteCountToDisplaySize( bytes );
如果需要將一個(gè)文件拷貝為另一個(gè)文件,或者需要將某個(gè)文件拷貝到某一個(gè)目錄中,可以使用如下的代碼:
拷貝為另一個(gè)文件:
Java代碼 
File src = new File( "test.dat" );
file dest = new File( "test.dat.bak" );
FileUtils.copyFile( src, dest );
拷貝到某一個(gè)目錄:
Java代碼 
File src = new File( "test.dat" );
File dir = new File( "./temp" );
FileUtils.copyFileToDirectory( src, dir );
使用Commons IO,你也可以很方便把字符串的內(nèi)容寫入文件中去,具體的過(guò)程不用怎么理會(huì):
Java代碼 
String string = "Blah blah blah";
File dest = new File( "test.tmp" );
FileUtils.writeStringToFile( dest, string);
當(dāng)然,有另外的一個(gè)功能,可以將URL的內(nèi)容存入文件中去:
Java代碼 
URL src = new URL( "http://www.nytimes.com" );
File dest = new File( "times.html" );
FileUtils.copyURLToFile( src, dest );
如果你需要?jiǎng)h除一個(gè)目錄下的所有內(nèi)容(包括其目錄),可以這樣做:
Java代碼 
File dir = new File( "temp" );
FileUtils.deleteDirectory( dir );
如果只想清空目錄下所有內(nèi)容,并不刪除該目錄,可以這樣寫:FileUtils.cleanDirectory( dir );
很簡(jiǎn)單地,可以得到一個(gè)目錄的大小:
Java代碼 
File dir = new File( "temp" );
long dirSize = FileUtils.sizeOfDirectory( );
如果你想得到某個(gè)目錄下所有以.txt結(jié)尾的文件,可以如下這樣做:
Java代碼 
import java.io.FilenameFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.lang.ArrayUtils;
File rootDir = new File(".");
FilenameFilter fileFilter = new SuffixFileFilter(".txt");
String[] txtFiles = rootDir.list( fileFilter );
System.out.println( ArrayUtils.toString( txtFiles ) );
舉另一個(gè)例子,怎樣列出目錄中以.htm和.html結(jié)尾的文件
Java代碼 
import org.apache.commons.io.filefilter.AndFileFilter;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.NotFileFilter;
import org.apache.commons.io.filefilter.OrFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.lang.ArrayUtils;
IOFileFilter htmlFilter =
new OrFileFilter( new SuffixFileFilter("htm"),new SuffixFileFilter("html") ); //復(fù)合兩個(gè)SuffixFileFilter
IOFileFilter notDirectory = new NotFileFilter( DirectoryFileFilter.INSTANCE );    //拒絕選擇目錄
FilenameFilter fileFilter = new AndFileFilter( htmlFilter, notDirectory );
String[] htmlFiles = rootDir.list(fileFilter);
System.out.println( ArrayUtils.toString( htmlFiles ));
注:文中代碼來(lái)之<<Jakarta Commons Cookbook>>一書第十章
文章待續(xù),會(huì)寫一些關(guān)于commons的筆錄下來(lái)
妙用Commons良藥<二>
談?wù)勗趺从胦rg.apache.commons.lang.StringUtils這一個(gè)類,講一下具體的幾個(gè)常用的方法
使用StringUtils.isBlank(),該方法在收到空字符串,零長(zhǎng)度字符串或全為空格的字符串時(shí)將返回true.它能通過(guò)返回true的方式優(yōu)雅地處理null.
Java代碼 
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 ) );
前面三個(gè)返回true,返回一個(gè)返回false
同樣,有一個(gè)StringUtils.isNotBlank()方法,當(dāng)一個(gè)字符串里面為空,或只包含空格,或是null時(shí),該方法將返回false,該方法的作用相當(dāng)于:
Java代碼 
if( variable != null &&  variable.length( ) > 0 && !variable.trim( ).equals("") ) {
// Do something
}
接下來(lái),介紹一個(gè)非常有用的方法StringUtils.abbreviate(),該方法接受一個(gè)字符串,如果可以的話就縮減它,如果要把一個(gè)字符串縮減為20個(gè)字符長(zhǎng),而原字符串長(zhǎng)度小于20個(gè)字符長(zhǎng),則該方法將返回原文本.若原字符串長(zhǎng)度大于20個(gè)字符,則顯示17個(gè)字符和3個(gè)省略號(hào).
Java代碼 
String test = "This is a test of the abbreviation."
String test2 = "Test"
System.out.println( StringUtils.abbreviate( test, 10 ) );
System.out.println( StringUtils.abbreviate( test2, 10 ) );
結(jié)果如下:
This is...
Test
另外一點(diǎn),可以使用StringUtils.split(),并提供一系列字符作為分隔符,StringUtils.chomp()去除字符串的末行終止序列.
接下來(lái),看一下StringUtils.substringBetween()方法,看下面一個(gè)例子:
Java代碼 
String variables = "{45}, {35}, {120}" ;
List numbers = new ArrayList( );
String variablesTemp = variables;
while( StringUtils.substringBetween( variablesTemp, "{", "}" ) != null ) {
String numberStr = StringUtils.substringBetween( variables, "{", "}" );
Double number = new Double( numberStr );
numbers.add( number );
variablesTemp = variablesTemp.substring( variablesTemp.indexOf(",") );
}
double sum = StatUtil.sum( ArrayUtils.toPrimitive( numbers.toArray( ) ) );
System.out.println( "Variables: " + variables + ", Sum: " + sum );
其結(jié)果如下:
Variable: {45}, {35}, {120}, Sum: 200
如果字符串的首尾含有需要清除的字符,可使用StringUtils.strip()清除它們.看下面例子:
Java代碼 
String original = "-------***---SHAZAM!---***-------";
String stripped = StringUtils.strip( original, "-*" );
System.out.println( "Stripped: " + stripped )
結(jié)果如下:
Stripped: SHAZAM!
增加一點(diǎn),StringUtils.reverse()可以實(shí)現(xiàn)字符串的反轉(zhuǎn),StringUtils.reverseDelimited()能夠分隔符反向排列字符串中的標(biāo)記.舉例:
Java代碼 
public Sentence reverseSentence(String sentence) {
String reversed = StringUtils.chomp( sentence, "." );
reversed = StringUtils.reverseDelimited( reversed, ' ' );
reversed = reversed + ".";
return reversed;
}
String sentence = "I am Susan."
String reversed = reverseSentence( sentence ) );
System.out.println( sentence );
System.out.println( reversed );
結(jié)果如下:
I am Susan.
Susan am I.:
當(dāng)然,還可以檢測(cè)字符串內(nèi)容,isNumeric( ),isAlpha(),isAlphanumeric(),and isAlphaSpace()這幾個(gè)方法用來(lái)驗(yàn)證用戶輸入的正確性,驗(yàn)證字符串的內(nèi)容是否為數(shù)字,是否字符,是否為數(shù)字+字符,是否為字符+空格.
如果你需要檢查一個(gè)大文件里面一個(gè)字符串出現(xiàn)的次數(shù),可以為StringUtils.countMatches()這一個(gè)方法,下面舉一個(gè)比較好的例子,不能將整個(gè)文件放入內(nèi)存中,相對(duì)比較合理的做法是一次一行地統(tǒng)計(jì),其方法如下:
Java代碼 
public  int testNumber() throws Exception{
File manuscriptFile = new File("c:\\test.txt");
Reader reader = new FileReader(manuscriptFile);
LineNumberReader lineReader = new LineNumberReader(reader);
int number = 0;
while(lineReader.ready()){
String line = StringUtils.lowerCase(lineReader.readLine());
number += StringUtils.countMatches(line, "test");
}
return number;
}
這一篇文章主要是介紹怎樣用Commons處理XMl文件
1、將XML文檔轉(zhuǎn)化為你想要的對(duì)象
可以使用org.apache.commons.digester.Digester來(lái)實(shí)現(xiàn)你想要的功能,其步驟如下:定義待匹配的模式,以及遇到之些模式時(shí)將執(zhí)行的動(dòng)作,通過(guò)Digester可以很容易地實(shí)現(xiàn)你自己的SAX解析器,并讓你無(wú)須處理復(fù)雜的SAX API,即可完成你想要的功能。Digester只是SAX外面的一個(gè)輕量級(jí)外殼,其解析的速度差不多和SAX一樣快的。
看一個(gè)XML文件:
Java代碼 
<?xml version="1.0"?>
<plays>
<play genre="tragedy" year="1603" language="english">
<name>Hamlet</name>
<author>William Shakespeare</author>
<summary>
Prince of Denmark freaks out, talks to ghost, gets into a
crazy nihilistic funk, and dies in a duel.
</summary>
<characters>
<character protagonist="false">
<name>Claudius</name>
<description>King of Denmark</description>
</character>
<character protagonist="true">
<name>Hamlet</name>
<descr> Son to the late, and nephew of the present king </descr>
</character>
<character protagonist="false">
<name>Horatio</name>
<descr>friend to Hamlet </descr>
</character>
</characters>
</play>
</plays>
為了解析這一個(gè)配置文件的內(nèi)容,相對(duì)應(yīng)地我們寫出下面的類:
Java代碼 
public class Play {
private String genre;
private String year;
private String language;
private String name;
private String author;
private String summary;
private List characters = new ArrayList( );
// accessors omitted for brevity
// Add method to support adding elements to characters.
public void addCharacter(Character character) {
characters.add( character );
}
}
public class Character {
private String name;
private String description;
private boolean protagonist;
// accessors omitted for brevity
}
下一步,寫出Digester的配置文件:
Java代碼 
<?xml version="1.0"?>
<digester-rules>
<pattern value="plays/play">
<object-create-rule classname="xml.digester.Play"/>
<set-next-rule methodname="add" paramtype="java.lang.Object"/>
<set-properties-rule/>
<bean-property-setter-rule pattern="name"/>
<bean-property-setter-rule pattern="summary"/>
<bean-property-setter-rule pattern="author"/>
<pattern value="characters/character">
<object-create-rule classname="xml.digester.Character"/>
<set-next-rule methodname="addCharacter"
paramtype="xml.digester.Character"/>
<set-properties-rule/>
<bean-property-setter-rule pattern="name"/>
<bean-property-setter-rule pattern="descr"
propertyname="description"/>
</pattern>
</pattern>
</digester-rules>
下面是其解析的過(guò)程,是不是相對(duì)于SAX來(lái)說(shuō)簡(jiǎn)單多了啊,呵呵:
Java代碼 
import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.DigesterLoader;
List plays = new ArrayList( );
// Create an instance of the Digester from the XML rule set
URL rules = getClass( ).getResource("./play-rules.xml");
Digester digester = DigesterLoader.createDigester(rules);
// Push a reference to the plays List on to the Stack
digester.push(plays);
// Parse the XML document
InputStream input = getClass( ).getResourceAsStream("./plays.xml");
Object root = digester.parse(input);
// The XML document contained one play "Hamlet"
Play hamlet = (Play) plays.get(0);
List characters = (List) hamlet.getCharacters( );
2、將Beans轉(zhuǎn)化為XML文檔
使用Commons Betwixt里面的org.apache.commons.betwixt.io.BeanWriter類可以把某個(gè)bean轉(zhuǎn)換為一個(gè)xml文檔,看下面的例子:
Java代碼 
Play play = new Play( );
// populatePlay populates all properties and nested Character objects
populatePlay( play );
// Write XML document
BeanWriter beanWriter = new BeanWriter( );
beanWriter.enablePrettyPrint( );
beanWriter.write( play );
System.out.println( beanWriter.toString( ) );
短短的幾行代碼就可以實(shí)現(xiàn)這一個(gè)功能了,簡(jiǎn)單吧;注意一下,beanWriter.enablePrettyPrint( )是啟用縮進(jìn)格式.
BeanWriter 類還用于向某個(gè)OutputStream或Writer寫入XML文檔,只要向其構(gòu)造函數(shù)傳一個(gè)Writer或OutputStream實(shí)例即可.
Java代碼 
import org.apache.commons.betwixt.io.BeanWriter
Play play = new Play( );
populatePlay( play );
Writer outputWriter = new FileWriter("test.dat");
BeanWriter beanWriter = new BeanWriter( outputWriter );
beanWriter.setEndOfLine( "\r\n" );
beanWriter.setIndent( "\t" );
beanWriter.enablePrettyPrint( );
beanWriter.write( play );
outputWriter.close( );
另外提示一下,beanWriter.setEndOfLine()方法可接受一個(gè)String作為行結(jié)束序列。beanWriter.setIndent()方法接受一個(gè)String參數(shù),該String將在BeanWriter中enablePrettyPrint()開啟縮進(jìn)時(shí)用作縮進(jìn)字符串。
3、轉(zhuǎn)換XML文檔為Beans
其實(shí)這一部分的內(nèi)容和第一部分的內(nèi)容差不多有點(diǎn)類似的,有興趣的朋友可以對(duì)比一下.
Commons Betwixt使用Commons Digester解析XML,而BeanReader即為Digester的一個(gè)子類。BeanReader使用自省機(jī)制以及類路徑中的Betwixt映射文件來(lái)創(chuàng)建了一組Digester規(guī)則.
舉例,有一個(gè)XMl文件就為前面第一個(gè)XML文件
Java代碼 
import org.apache.commons.betwixt.io.BeanReader;
InputStream customPlay =
getClass( ).getResourceAsStream("./customized-play.xml");
BeanReader beanReader = new BeanReader( );
beanReader.getXMLIntrospector( ).setWrapCollectionsInElement(false);
beanReader.registerBeanClass(Play.class);
Play play = (Play) beanReader.parse( customPlay );
注:些文章中的代碼來(lái)自<<Jakarta Commons Cookbook>>第六章內(nèi)容
妙用Commons良藥<四>
談一談Math包的一點(diǎn)內(nèi)容,和怎樣對(duì)屬性文件,xml文件進(jìn)行訪問(wèn)
1、關(guān)于org.apache.commons.lang.math的應(yīng)用
可使用Commons Lang的NumberUtils.max()和NumberUtils.min()方法來(lái)從基本類型數(shù)組(如
Java代碼 
double[],float[],long[],int[],short[],byte[])中檢索出最小或最大值.舉例:
import org.apache.commons.lang.math.NumberUtils;
double[] array = {0.2, 0.4, 0.5, -3.0, 4.223, 4.226};
double max = NumberUtils.max( array ); // returns 4.226
double min = NumberUtils.min( array ); // returns -3.0
當(dāng)然,你可以處理數(shù)學(xué)的范圍,需要為某個(gè)變量定義一組可接受的值,并檢測(cè)該變量值是否落在指定的范圍內(nèi).Range是一個(gè)接口,定義了一個(gè)簡(jiǎn)單的數(shù)值范圍,它有幾個(gè)不同的實(shí)現(xiàn),如NumberRange,DoubleRange,FloatRange,IntRange以及LongRange等等.
Java代碼 
import org.apache.commons.lang.math.DoubleRange;
import org.apache.commons.lang.math.Range;
Range safeSpeed = new DoubleRange( 0.0, 65.0 );
double currentSpeed = getCurrentSpeed( );
if( !safeSpeed.containsDouble( currentSpeed ) ) {
System.out.println( "Warning, current speed is unsafe." );
}
如果你想生成一個(gè)隨機(jī)數(shù),可以這樣寫:
Java代碼 
import org.apache.commons.lang.math.RandomUtils;
// Create a random integer between 0 and 30
int maxVal = 30;
int randomInt = RandomUtils.nextInt( maxVal );
其作用相當(dāng)于:int randomInt = (int) Math.floor( (Math.random( ) * (double) maxVal) );
此外提示一點(diǎn),RandomUtils.nextBoolean()可以返回一個(gè)隨機(jī)的boolean變量
2、關(guān)于Jakarta Commons Math包一點(diǎn)應(yīng)用
舉一個(gè)例子,如下:
Java代碼 
import org.apache.commons.math.stat.StatUtils;
double[] values = new double[] { 2.3, 5.4, 6.2, 7.3, 23.3 };
System.out.println( "min: " + StatUtils.min( values ) );
System.out.println( "max: " + StatUtils.max( values ) );
System.out.println( "平均值: " + StatUtils.mean( values ) );
System.out.println( "積: " + StatUtils.product( values ) );
System.out.println( "和: " + StatUtils.sum( values ) );
System.out.println( "方差: " + StatUtils.variance( values ) );
當(dāng)然,這一個(gè)包也可以處理復(fù)數(shù),矩陣,統(tǒng)計(jì)以及線性方程,具體的用法參考官方的文檔
3、使用Commons Configuration包配置應(yīng)用程序
如果想訪問(wèn)屬性文件的話,可以運(yùn)用PropertiesConfiguration這一個(gè)類:
屬性文件如下:
speed=23.332
names=Bob,Gautam,Jarret,Stefan
correct=false
Java代碼 
其代碼如下:
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
Configuration config = new PropertiesConfiguration( "test.properties" );
float speed = config.getFloat("speed"));
List names = config.getList("names"));
boolean correct = config.getBoolean("correct");
如果想訪問(wèn)一個(gè)xml文件里面具體的屬性,可以使用XMLConfiguration的一個(gè)實(shí)現(xiàn)從某個(gè)文檔中加載配置參數(shù)。舉例如下:
其配置文件:
Java代碼 
<?xml version="1.0" encoding="ISO-8859-1" ?>
<engine-config>
<start-criteria>
<criteria type="critical">
Temperature Above -10 Celsius
</criteria>
<criteria> Fuel tank is not empty </criteria>
</start-criteria>
<name>
<first>Tom</first>
<last>Payne</last>
</name>
<horsepower>42</horsepower>
</engine-config>
具體訪問(wèn)的代碼如下:
Java代碼 
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.DOMConfiguration;
String resource = "com/discursive/jccook/configuration/global.xml";
Configuration config = new DOMConfiguration(resource);
// Retrieve a list of all Criteria elements
List startCriteria = config.getList("start-criteria.criteria");
// Retrieve the value of the first criteria element
String firstCriteria = config.getString("start-criteria.criteria(0)");
// Retrieve the type attribute of the first criteria element
String firstCriteriaType = config.getString("start-criteria.criteria(0)[@type]");
// Retrieve the horsepower as an int
int horsepower = config.getInt("horsepower");
這一篇文章主要是講一下關(guān)于Commons開源項(xiàng)目中其Commons BeanUtils的一些相關(guān)的用法.
1、復(fù)制Bean屬性
如果你有兩個(gè)相同的Bean的實(shí)例,并需要將其中的一個(gè)bean屬性復(fù)制到另一個(gè)中去,調(diào)用PropertyUtils.copyProperties()即可,這一個(gè)方法經(jīng)常在使用struts,hibernate等框架的時(shí)候常常用到.舉例:
Java代碼 
import org.apache.commons.beanutils.PropertyUtils;
Book book = new Book( );
book.setName( "Prelude to Foundation" );
book.setAuthorName( "Asimov" );
Book destinationBook = new Book( );
PropertyUtils.copyProperties( destinationBook, book );
請(qǐng)注意,該方法是將相同的引用對(duì)象賦給目的的bean,并沒(méi)有克隆bean屬性的值.
2、怎樣使用Map來(lái)封裝Bean
假如你需要將bean的屬性傳入Map
可使用BeanMap類封裝任何Bean。該Map通過(guò)內(nèi)省機(jī)制提供了對(duì)bean屬性的訪問(wèn),使得其看上去像是Map中成對(duì)的鍵與值.舉例:
Java代碼 
import java.util.*;
import org.apache.commons.beanutils.PropertyUtils;
// Create a Person and a Book bean instance
Person person = new Person( );
person.setName( "Some Dude" );
Book book = new Book( );
book.setName( "Some Silly Computer Book" );
book.setAuthor( person );
// Describe both beans with a Map
Map bookMap = PropertyUtils.describe( book );
Map authorMap = PropertyUtils.describe( bookMap.get("book") );
System.out.println( "Book Name: " + bookMap.get( "name" ) );
System.out.println( "Author Name: " + authorMap.get( "name" ) );
注意一點(diǎn),如果你修改了BeanMap的時(shí)候,你也就修改了其內(nèi)部的Bean.
還有常用的clear(),setBean(Object bean)等方法
3、可以根據(jù)Bean的屬性來(lái)比較Beans
使用BeanComparator可根據(jù)bean屬性來(lái)比較兩個(gè)Bean.興例如下:
Java代碼 
import java.util.*;
import org.apache.commons.beanutils.BeanComparator;
Country country1 = new Country( );
country1.setName( "India" );
Country country2 = new Country( );
country2.setName( "Pakistan" );
Country country3 = new Country( );
country3.setName( "Afghanistan" );
// Create a List of Country objects
Country[] countryArray = new Country[] { country1, country2, country3 };
List countryList = Arrays.asList( countryArray );
// Sort countries by name
Comparator nameCompare = new BeanComparator( "name" );
Collections.sort( countryList, nameCompare );
System.out.println( "Sorted Countries:" );
Iterator countryIterator = countryList.iterator( );
while( countryIterator.hasNext( ) ) {
Country country = (Country) countryIterator.next( );
System.out.println( "\tCountry: " + country.getName( ) );
}
結(jié)果顯示如下:
引用
Sorted Countries:
Country: Afghanistan
Country: India
Country: Pakistan
注:文章中的代碼均來(lái)之<<Jakarta  Commons Cookbook>>一書第三章
妙用Commons良藥 <六>
1、定義toString(),hashCode(),equals()等內(nèi)容
toString()方法舉例:
Java代碼 
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
public String toString( ) {
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append("lastName", lastName)
.append("firstName", firstName)
.toString( );
}
提示一點(diǎn),ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE),第二個(gè)參數(shù)當(dāng)然也可以為ToStringStyle.DEFAULT_STYLE,ToStringStyle.NO_FIELD_NAMES_STYLE和ToStringStyle.SIMPLE_STYLE
hashCode()與equals()方法舉例:
Java代碼 
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
public class PoliticalCandidate {
public int hashCode( ) {
return new HashCodeBuilder(17, 37) //兩個(gè)不為0且非偶的質(zhì)數(shù)
.append(firstName)
.append(lastName).toHashCode( );
}
public boolean equals(Object o) {
boolean equals = false;
if ( o != null &&
PoliticalCandidate.class.isAssignableFrom(o) ) {
PoliticalCandidate pc = (PoliticalCandidate) o;
equals = (new EqualsBuilder( )
.append(firstName, ps.firstName)
.append(lastName, ps.lastName)).isEquals( );
}
return equals;
}
}
2、操作數(shù)組內(nèi)容
ArrayUtils.toString()方法可以輸入數(shù)組內(nèi)容,此方法接受任意一個(gè)數(shù)組作為參數(shù)并輸出其內(nèi)容,輸出時(shí)所有元素位于大括號(hào),中間逗號(hào)隔開.舉例:
Java代碼 
int[] intArray = new int[] { 2, 3, 4, 5, 6 };
int[] multiDimension = new int[][] { { 1, 2, 3 }, { 2, 3 }, {5, 6, 7} };
System.out.println( "intArray: " + ArrayUtils.toString( intArray ) );
System.out.println( "multiDimension: " + ArrayUtils.toString( multiDimension ) );
使用ArrayUtils.reverse()方法可以反轉(zhuǎn)一個(gè)數(shù)組.
使用ArrayUtils.toObject()和ArrayUtils.toPrimitive()兩個(gè)方法,即可互相轉(zhuǎn)換基本類型數(shù)組和對(duì)象數(shù)組。
當(dāng)然,Commons也提供了方便的方法,可以在數(shù)組中搜索特定項(xiàng).
使用ArrayUtils.contains()方法可以判定數(shù)組是否存在指完元素.當(dāng)然有兩個(gè)比較實(shí)用的方法ArrayUtils.lastIndexOf()和ArrayUtils.indexOf(),舉例如下:
Java代碼 
import org.apache.commons.lang.ArrayUtils;
String[] stringArray = { "Red", "Orange", "Blue", "Brown", "Red" };
boolean containsBlue = ArrayUtils.contains( stringArray, "Blue" );
int indexOfRed = ArrayUtils.indexOf( stringArray, "Red");
int lastIndexOfRed = ArrayUtils.lastIndexOf( string, "Red" );
System.out.println( "Array contains 'Blue'? " + containsBlue );
System.out.println( "Index of 'Red'? " + indexOfRed );
System.out.println( "Last Index of 'Red'? " + lastIndexOfRed );
結(jié)果如下:
引用
Array contains 'Blue'? true
Index of 'Red'? 0
Last Index of 'Red'? 4
另外一個(gè)功能,你可以很容易將一個(gè)二維對(duì)象數(shù)組成一個(gè)Map對(duì)象,只需要ArrayUtils.toMap()這一個(gè)方法即可.舉例如下:
Java代碼 
import org.apache.commons.lang.ArrayUtils;
Object[] weightArray =
new Object[][] { {"H" , new Double( 1.007)},
{"He", new Double( 4.002)},
{"Li", new Double( 6.941)},
{"Be", new Double( 9.012)},
{"B",  new Double(10.811)},
{"Ne", new Double(20.180)} };
Map weights = ArrayUtils.toMap( weightArray );
Double hydrogenWeight = map.get( "H" );
3、怎樣格式化日期
如果你想格式化一個(gè)的時(shí)候,需要注意一下JDK中自帶的SimpleDatFormat類不是線程安全的。你可以用FastDateFormat或DateFormatUtils來(lái)實(shí)現(xiàn)你想要的功能。如果在你的系統(tǒng)中有多個(gè)線程共享一個(gè)SimpleDatFormat實(shí)例,建議你馬上改為SimpleDatFormat類.
舉例:
Java代碼 
Date now = new Date( );
String isoDT = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format( now );
System.out.println( "It is currently: " + isoDT );
結(jié)果是:
引用
It is currently: 2004-03-26T16:20:00-07:00
又舉一個(gè)例子,如下:
Java代碼 
FastDateFormat formatter =
new FastDateFormat( "yyyy-mm", TimeZone.getDefault( ), Locale.getDefault( ));
String output = formatter.format( new Date( ) );
// output equals "2003-10"
DateFormatUtils的時(shí)間格式如下:
Java代碼 
ISO_DATE_FORMAT
yyyy-MM-dd"2004-01-02"
ISO_DATE_TIME_ZONE_FORMAT
yyyy-MM-ddZZ"2004-01-02-07:00"
ISO_DATETIME_FORMAT
yyyy-MM-dd'T'HH:mm:ss"2004-01-02T23:22:12"
ISO_DATETIME_TIME_ZONE_FORMAT
yyyy-MM-dd'T'HH:mm:ssZZ"2004-01-02T21:13:45-07:00"
ISO_TIME_FORMAT
'T'HH:mm:ss"T04:23:22"
ISO_TIME_NO_T_FORMAT
HH:mm:ss"05:12:34"
ISO_TIME_NO_T_TIME_ZONE_FORMAT
HH:mm:ssZZ"12:32:22-07:00"
ISO_TIME_TIME_ZONE_FORMAT
'T'HH:mm:ssZZ"T18:23:22-07:00"
SMTP_DATETIME_FORMAT
EEE, dd MMM yyyy HH:mm:ss Z"Wed, 01 Feb 2004 20:03:01 CST"
注:本文章代碼均來(lái)自<<Jarkata Commonss Cookbook>>一書第一章的內(nèi)容,下一講主要說(shuō)一下Functors方面的內(nèi)容
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊舉報(bào)。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
commons-lang
如何在Java中填充字符串?
apache commons常用工具類
11 個(gè)簡(jiǎn)單的 Java 性能調(diào)優(yōu)技巧
Java工具類之Apache的Commons Lang和BeanUtils
Apache Commons工具集簡(jiǎn)介
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長(zhǎng)圖 關(guān)注 下載文章
綁定賬號(hào)成功
后續(xù)可登錄賬號(hào)暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服