MY Top List of Java Tools

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="ProgId" content="Word.Document"> <meta name="Generator" content="Microsoft Word 11"> <meta name="Originator" content="Microsoft Word 11"> <link rel="File-List" href="file:///C:%5CDOCUME%7E1%5Cguofc%5CLOCALS%7E1%5CTemp%5Cmsohtml1%5C01%5Cclip_filelist.xml"> <link rel="Edit-Time-Data" href="file:///C:%5CDOCUME%7E1%5Cguofc%5CLOCALS%7E1%5CTemp%5Cmsohtml1%5C01%5Cclip_editdata.mso"> <!--[if !mso]> <style> v/:* {behavior:url(#default#VML);} o/:* {behavior:url(#default#VML);} w/:* {behavior:url(#default#VML);} .shape {behavior:url(#default#VML);} </style> <![endif]--><!--[if gte mso 9]><xml> <w:WordDocument> <w:View>Normal</w:View> <w:Zoom>0</w:Zoom> <w:PunctuationKerning/> <w:DrawingGridVerticalSpacing>7.8 磅</w:DrawingGridVerticalSpacing> <w:DisplayHorizontalDrawingGridEvery>0</w:DisplayHorizontalDrawingGridEvery> <w:DisplayVerticalDrawingGridEvery>2</w:DisplayVerticalDrawingGridEvery> <w:ValidateAgainstSchemas/> <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid> <w:IgnoreMixedContent>false</w:IgnoreMixedContent> <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText> <w:Compatibility> <w:SpaceForUL/> <w:BalanceSingleByteDoubleByteWidth/> <w:DoNotLeaveBackslashAlone/> <w:ULTrailSpace/> <w:DoNotExpandShiftReturn/> <w:AdjustLineHeightInTable/> <w:BreakWrappedTables/> <w:SnapToGridInCell/> <w:WrapTextWithPunct/> <w:UseAsianBreakRules/> <w:DontGrowAutofit/> <w:UseFELayout/> </w:Compatibility> <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel> </w:WordDocument> </xml><![endif]--><!--[if gte mso 9]><xml> <w:LatentStyles DefLockedState="false" LatentStyleCount="156"> </w:LatentStyles> </xml><![endif]--><style> <!-- /* Font Definitions */ @font-face {font-family:宋体; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-alt:SimSun; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} @font-face {font-family:"/@宋体"; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0cm; margin-bottom:.0001pt; text-align:justify; text-justify:inter-ideograph; mso-pagination:none; font-size:10.5pt; mso-bidi-font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:宋体; mso-font-kerning:1.0pt;} a:link, span.MsoHyperlink {color:blue; text-decoration:underline; text-underline:single;} a:visited, span.MsoHyperlinkFollowed {color:purple; text-decoration:underline; text-underline:single;} /* Page Definitions */ @page {mso-page-border-surround-header:no; mso-page-border-surround-footer:no;} @page Section1 {size:595.3pt 841.9pt; margin:72.0pt 90.0pt 72.0pt 90.0pt; mso-header-margin:42.55pt; mso-footer-margin:49.6pt; mso-paper-source:0; layout-grid:15.6pt;} div.Section1 {page:Section1;} /* List Definitions */ @list l0 {mso-list-id:481697913; mso-list-template-ids:-75352008;} @list l1 {mso-list-id:686254597; mso-list-template-ids:-23688064;} @list l2 {mso-list-id:1083181047; mso-list-template-ids:1994446186;} @list l3 {mso-list-id:1566799377; mso-list-template-ids:1202461344;} ol {margin-bottom:0cm;} ul {margin-bottom:0cm;} --></style>

Lack of imagination is one of our worst sins as software developers. We do the same things over and over again, but we rarely modify our ways - me at least. After some years, these are the tools that made it into my tricks box for everyday tasks. Tiresome operations are not my thing.

Chances are you are already using at least some of these, but here we go anyways:

StringUtils



The bread and butter of the commons-lang library, this utility class includes some methods that should seriously have been included in String long time ago.


StringUtils.isEmpty(null) && StringUtils.isEmpty(""); // true
StringUtils.isBlank(" /n/t"); // true
StringUtils.substringAfterLast("foo.bar.baz", "."); // "baz"
StringUtils.substringBeforeLast("foo.bar.baz", "."); // "foo.bar"
StringUtils.split("foo.bar.baz", '.'); // { "foo", "bar", "baz" }
StringUtils.split("foo, bar,baz", ", "); // { "foo", "bar", "baz" }
StringUtils.leftPad("1", 3, '0'); // "001"

IOUtils and FileUtils



A must-have for the rare occasions where you need to manipulate files by hand. Both are pretty much alike (FileUtils for File, IOUtils for InputStream and Reader classes) and come bundled in commons-io.


File file1;
File file2;
InputStream inputStream;
OutputStream outputStream;

// copy one file into another
FileUtils.copyFile(file1, file2);
IOUtils.copy(inputStream, outputStream);

// read a file into a String
String s1 = FileUtils.readFileToString(file1);
String s2 = IOUtils.toString(inputStream);

// read a file into a list of Strings, one item per line
List<String> l1 = FileUtils.readLines(file1);
List<String> l2 = IOUtils.readLines(inputStream);

// put this in your finally() clause after manipulating streams
IOUtils.closeQuietly(inputStream);

// return the list of xml and text files in the specified folder and any subfolders
Collection<File> c1 = FileUtils.listFiles(file1, { "xml", "txt" }, true);

// copy one folder and its contents into another
FileUtils.copyDirectoryToDirectory(file1, file2);

// delete one folder and its contents
FileUtils.deleteDirectory(file1);

Google collections



This is the best implementation of a collections extension that I know of. Some of these are shouting to be included in the JDK:


// create an ArrayList with three arguments
List<String> list = Lists.newArrayList("foo", "bar", "baz");

// notice that there is no generics or class cast,
// and still this line does not generate a warning.
Set<String> s = Sets.newConcurrentHashSet();

// intersect and union are basic features of a Set, if you ask me
Set<String> s = Sets.intersect(s1, s2);

// Example of multiple values in a Map
ListMultimap<String, Validator> validators = new ArrayListMultimap<String, Validator>();
validators.put("save", new RequiredValidator());
validators.put("save", new StringValidator());
validators.put("delete", new NumberValidator());

validators.get("save"); // { RequiredValidator, StringValidator }
validators.get("foo"); // empty List (not null)
validators.values(); // { RequiredValidator, StringValidator, NumberValidator }

java.util.concurrent



Not everybody needs the heavy lifting of java.util.concurrent, but the concurrent collections are handy:


// a map that may be modified (by the same or different thread) while being iterated
Map<String, Something> repository = new ConcurrentHashMap<String, Something>();

// same with lists. This one is only available with Java 6
List<Something> list = new CopyOnWriteArrayList<Something>();



Hardly a large toolbox, is it? If your favourite library is missing, feel free to add it :)

Authorcoloma

ProfileI'm a java architect that shares some development time at Extrema Sistemas, where Loom was born - the web framework that sets a new standard for "Kicks Ass".

其中StirngUtilshttp://commons.apache.org/ lang类库中的一个类,FileUtilsIOUtilsio包中的一个类。

Google collections http://code.google.com/p/google-collections/中,读者可以从网站上下载,加入到开发过程中。

下面有一个中文版本:

我的顶级JAVA工具单

作为一个软件开发者,缺乏想象力是最严重的罪过之一。我们经常把事情重复做一遍又一遍,但是我们很少改变这种方式,至少我是这样。经过这些年开发,在我的工具箱里面有了一些每个项目我都需要用到的工具,烦人的重复工作不再是我的事。

下面这些工具也许你已经用到,让我来仔细介绍它们:

StringUitls

这是象面包和奶油一样必须的通用语言库,这个实用工具类包括一些很早以前在String中未包含的重要方法。

Java代码 <!--[if gte vml 1]><v:shapetype id="_x0000_t75" coordsize="21600,21600" o:spt="75" o:preferrelative="t" path="m@4@5l@4@11@9@11@9@5xe" filled="f" stroked="f"> <v:stroke joinstyle="miter"/> <v:formulas> <v:f eqn="if lineDrawn pixelLineWidth 0"/> <v:f eqn="sum @0 1 0"/> <v:f eqn="sum 0 0 @1"/> <v:f eqn="prod @2 1 2"/> <v:f eqn="prod @3 21600 pixelWidth"/> <v:f eqn="prod @3 21600 pixelHeight"/> <v:f eqn="sum @0 0 1"/> <v:f eqn="prod @6 1 2"/> <v:f eqn="prod @7 21600 pixelWidth"/> <v:f eqn="sum @8 21600 0"/> <v:f eqn="prod @7 21600 pixelHeight"/> <v:f eqn="sum @10 21600 0"/> </v:formulas> <v:path o:extrusionok="f" gradientshapeok="t" o:connecttype="rect"/> <o:lock v:ext="edit" aspectratio="t"/> </v:shapetype><v:shape id="_x0000_i1025" type="#_x0000_t75" alt="复制代码" href="http://www.javaeye.com/news/4013-my-list-of-top-java-tool" title="&quot;复制代码&quot;" style='width:10.5pt;height:11.25pt' o:button="t"> <v:imagedata src="file:///C:/DOCUME~1/guofc/LOCALS~1/Temp/msohtml1/01/clip_image001.gif" o:href="http://www.javaeye.com/images/icon_copy.gif"/> </v:shape><![endif]--><!--[if !vml]--><!--[endif]-->

  1. StringUtils.isEmpty(null)&&StringUtils.isEmpty("");//true

  2. StringUtils.isBlank("/n/t");//true

  3. StringUtils.substringAfterLast("foo.bar.baz",".");//"baz"

  4. StringUtils.substringBeforeLast("foo.bar.baz",".");//"foo.bar"

  5. StringUtils.split("foo.bar.baz",'.');//{"foo","bar","baz"}

  6. StringUtils.split("foo,bar,baz",",");//{"foo","bar","baz"}

  7. StringUtils.leftPad("1",3,'0');//"001"

StringUtils.isEmpty(null) && StringUtils.isEmpty(""); // true

StringUtils.isBlank(" /n/t"); // true

StringUtils.substringAfterLast("foo.bar.baz", "."); // "baz"

StringUtils.substringBeforeLast("foo.bar.baz", "."); // "foo.bar"

StringUtils.split("foo.bar.baz", '.'); // { "foo", "bar", "baz" }

StringUtils.split("foo, bar,baz", ", "); // { "foo", "bar", "baz" }

StringUtils.leftPad("1", 3, '0'); // "001"



IOUtils and FileUtils

在一种当你需要手动操作多个文件罕见情况下必须具备的工具,这两个工具很相似(FileUtils操作文件,IOUtils操作InputStreamReader classes),和捆绑常用IO.

Java代码 <!--[if gte vml 1]><v:shape id="_x0000_i1026" type="#_x0000_t75" alt="复制代码" href="http://www.javaeye.com/news/4013-my-list-of-top-java-tool" title="&quot;复制代码&quot;" style='width:10.5pt;height:11.25pt' o:button="t"> <v:imagedata src="file:///C:/DOCUME~1/guofc/LOCALS~1/Temp/msohtml1/01/clip_image001.gif" o:href="http://www.javaeye.com/images/icon_copy.gif"/> </v:shape><![endif]--><!--[if !vml]--><!--[endif]-->

  1. Filefile1;

  2. Filefile2;

  3. InputStreaminputStream;

  4. OutputStreamoutputStream;

  5. //copyonefileintoanother

  6. FileUtils.copyFile(file1,file2);

  7. IOUtils.copy(inputStream,outputStream);

  8. //readafileintoaString

  9. Strings1=FileUtils.readFileToString(file1);

  10. Strings2=IOUtils.toString(inputStream);

  11. //readafileintoalistofStrings,oneitemperline

  12. List<String>l1=FileUtils.readLines(file1);

  13. List<String>l2=IOUtils.readLines(inputStream);

  14. //putthisinyourfinally()clauseaftermanipulatingstreams

  15. IOUtils.closeQuietly(inputStream);

  16. //returnthelistofxmlandtextfilesinthespecifiedfolderandanysubfolders

  17. Collection<File>c1=FileUtils.listFiles(file1,{"xml","txt"},true);

  18. //copyonefolderanditscontentsintoanother

  19. FileUtils.copyDirectoryToDirectory(file1,file2);

  20. //deleteonefolderanditscontents

  21. FileUtils.deleteDirectory(file1);

File file1;

File file2;

InputStream inputStream;

OutputStream outputStream;

// copy one file into another

FileUtils.copyFile(file1, file2);

IOUtils.copy(inputStream, outputStream);

// read a file into a String

String s1 = FileUtils.readFileToString(file1);

String s2 = IOUtils.toString(inputStream);

// read a file into a list of Strings, one item per line

List<String> l1 = FileUtils.readLines(file1);

List<String> l2 = IOUtils.readLines(inputStream);

// put this in your finally() clause after manipulating streams

IOUtils.closeQuietly(inputStream);

// return the list of xml and text files in the specified folder and any subfolders

Collection<File> c1 = FileUtils.listFiles(file1, { "xml", "txt" }, true);

// copy one folder and its contents into another

FileUtils.copyDirectoryToDirectory(file1, file2);

// delete one folder and its contents

FileUtils.deleteDirectory(file1);



Google collections

这是我所知道的最好的扩展实现包,其中一些被社区叫嚣着要加入JDK

Java代码 <!--[if gte vml 1]><v:shape id="_x0000_i1027" type="#_x0000_t75" alt="复制代码" href="http://www.javaeye.com/news/4013-my-list-of-top-java-tool" title="&quot;复制代码&quot;" style='width:10.5pt;height:11.25pt' o:button="t"> <v:imagedata src="file:///C:/DOCUME~1/guofc/LOCALS~1/Temp/msohtml1/01/clip_image001.gif" o:href="http://www.javaeye.com/images/icon_copy.gif"/> </v:shape><![endif]--><!--[if !vml]--><!--[endif]-->

  1. //createanArrayListwiththreearguments

  2. List<String>list=Lists.newArrayList("foo","bar","baz");

  3. //noticethatthereisnogenericsorclasscast,

  4. //andstillthislinedoesnotgenerateawarning.

  5. Set<String>s=Sets.newConcurrentHashSet();

  6. //intersectandunionarebasicfeaturesofaSet,ifyouaskme

  7. Set<String>s=Sets.intersect(s1,s2);

  8. //ExampleofmultiplevaluesinaMap

  9. ListMultimap<String,Validator>validators=newArrayListMultimap<String,Validator>();

  10. validators.put("save",newRequiredValidator());

  11. validators.put("save",newStringValidator());

  12. validators.put("delete",newNumberValidator());

  13. validators.get("save");//{RequiredValidator,StringValidator}

  14. validators.get("foo");//emptyList(notnull)

  15. validators.values();//{RequiredValidator,StringValidator,NumberValidator}

// create an ArrayList with three arguments

List<String> list = Lists.newArrayList("foo", "bar", "baz");

// notice that there is no generics or class cast,

// and still this line does not generate a warning.

Set<String> s = Sets.newConcurrentHashSet();

// intersect and union are basic features of a Set, if you ask me

Set<String> s = Sets.intersect(s1, s2);

// Example of multiple values in a Map

ListMultimap<String, Validator> validators = new ArrayListMultimap<String, Validator>();

validators.put("save", new RequiredValidator());

validators.put("save", new StringValidator());

validators.put("delete", new NumberValidator());

validators.get("save"); // { RequiredValidator, StringValidator }

validators.get("foo"); // empty List (not null)

validators.values(); // { RequiredValidator, StringValidator, NumberValidator }



java.util.concurrent

不是每个人都需要这么重的java.util.concurrent,但是很好用:

Java代码 <!--[if gte vml 1]><v:shape id="_x0000_i1028" type="#_x0000_t75" alt="复制代码" href="http://www.javaeye.com/news/4013-my-list-of-top-java-tool" title="&quot;复制代码&quot;" style='width:10.5pt;height:11.25pt' o:button="t"> <v:imagedata src="file:///C:/DOCUME~1/guofc/LOCALS~1/Temp/msohtml1/01/clip_image001.gif" o:href="http://www.javaeye.com/images/icon_copy.gif"/> </v:shape><![endif]--><!--[if !vml]--><!--[endif]-->

  1. //amapthatmaybemodified(bythesameordifferentthread)whilebeingiterated

  2. Map<String,Something>repository=newConcurrentHashMap<String,Something>();

  3. //samewithlists.ThisoneisonlyavailablewithJava6

  4. List<Something>list=newCopyOnWriteArrayList<Something>();

// a map that may be modified (by the same or different thread) while being iterated

Map<String, Something> repository = new ConcurrentHashMap<String, Something>();

// same with lists. This one is only available with Java 6

List<Something> list = new CopyOnWriteArrayList<Something>();



你有好的工具推荐吗?欢迎留言。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值