20個非常有用的Java程序片段

1. 字符串有整型的相互轉換

Stringa=String.valueOf(2);//integertonumericstring
inti=Integer.parseInt(a);//numericstringtoanint

2. 向文件末尾添加內容

BufferedWriterout=null;
try{
out=newBufferedWriter(newFileWriter(”filename”,true));
out.write(”aString”);
}catch(IOExceptione){
//errorprocessingcode
}finally{
if(out!=null){
out.close();
}
}

3. 得到當前方法的名字

StringmethodName=Thread.currentThread().getStackTrace()[1].getMethodName();

4. 轉字符串到日期

java.util.Date=java.text.DateFormat.getDateInstance().parse(dateString);

或者是:

SimpleDateFormatformat=newSimpleDateFormat("dd.MM.yyyy");
Datedate=format.parse(myString);

5. 使用JDBC鏈接Oracle

publicclassOracleJdbcTest
{
StringdriverClass="oracle.jdbc.driver.OracleDriver";
Connectioncon;
publicvoidinit(FileInputStreamfs)throwsClassNotFoundException,SQLException,FileNotFoundException,IOException
{
Propertiesprops=newProperties();
props.load(fs);
Stringurl=props.getProperty("db.url");
StringuserName=props.getProperty("db.user");
Stringpassword=props.getProperty("db.password");
Class.forName(driverClass);
con=DriverManager.getConnection(url,userName,password);
}
publicvoidfetch()throwsSQLException,IOException
{
PreparedStatementps=con.prepareStatement("selectSYSDATEfromdual");
ResultSetrs=ps.executeQuery();
while(rs.next())
{
//dothethingyoudo
}
rs.close();
ps.close();
}
publicstaticvoidmain(String[]args)
{
OracleJdbcTesttest=newOracleJdbcTest();
test.init();
test.fetch();
}
}

6.把 Java util.Date轉成 sql.Date

java.util.DateutilDate=newjava.util.Date();
java.sql.DatesqlDate=newjava.sql.Date(utilDate.getTime());

7. 使用NIO進行快速的文件拷貝

publicstaticvoidfileCopy(Filein,Fileout)
throwsIOException
{
FileChannelinChannel=newFileInputStream(in).getChannel();
FileChanneloutChannel=newFileOutputStream(out).getChannel();
try
{
//inChannel.transferTo(0,inChannel.size(),outChannel);//original--apparentlyhastroublecopyinglargefilesonWindows
//magicnumberforWindows,64Mb-32Kb)
intmaxCount=(64*1024*1024)-(32*1024);
longsize=inChannel.size();
longposition=0;
while(position<size)
{
position+=inChannel.transferTo(position,maxCount,outChannel);
}
}
finally
{
if(inChannel!=null)
{
inChannel.close();
}
if(outChannel!=null)
{
outChannel.close();
}
}
}


150143snt4k4k3llug2n4n.jpg


9.創建 JSON 格式的數據

請先閱讀這篇文章瞭解一些細節,

並下面這個JAR 文件:json-rpc-1.0.jar (75 kb)

importorg.json.JSONObject;
...
...
JSONObjectjson=newJSONObject();
json.put("city","Mumbai");
json.put("country","India");
...
Stringoutput=json.toString();
...





15. 創建ZIP和JAR文件

importjava.util.zip.*;
importjava.io.*;
publicclassZipIt{
publicstaticvoidmain(Stringargs[])throwsIOException{
if(args.length<2){
System.err.println("usage:javaZipItZip.zipfile1file2file3");
System.exit(-1);
}
FilezipFile=newFile(args[0]);
if(zipFile.exists()){
System.err.println("Zipfilealreadyexists,pleasetryanother");
System.exit(-2);
}
FileOutputStreamfos=newFileOutputStream(zipFile);
ZipOutputStreamzos=newZipOutputStream(fos);
intbytesRead;
byte[]buffer=newbyte[1024];
CRC32crc=newCRC32();
for(inti=1,n=args.length;i<n;i++){
Stringname=args;
Filefile=newFile(name);
if(!file.exists()){
System.err.println("Skipping:"+name);
continue;
}
BufferedInputStreambis=newBufferedInputStream(
newFileInputStream(file));
crc.reset();
while((bytesRead=bis.read(buffer))!=-1){
crc.update(buffer,0,bytesRead);
}
bis.close();
//Resettobeginningofinputstream
bis=newBufferedInputStream(
newFileInputStream(file));
ZipEntryentry=newZipEntry(name);
entry.setMethod(ZipEntry.STORED);
entry.setCompressedSize(file.length());
entry.setSize(file.length());
entry.setCrc(crc.getValue());
zos.putNextEntry(entry);
while((bytesRead=bis.read(buffer))!=-1){
zos.write(buffer,0,bytesRead);
}
bis.close();
}
zos.close();
}
}

16. 解析/讀取XML 文件

XML文件

<?xmlversion="1.0"?>
<students>
<student>
<name>John</name>
<grade>B</grade>
<age>12</age>
</student>
<student>
<name>Mary</name>
<grade>A</grade>
<age>11</age>
</student>
<student>
<name>Simon</name>
<grade>A</grade>
<age>18</age>
</student>
</students>

Java代碼

packagenet.viralpatel.java.xmlparser;
importjava.io.File;
importjavax.xml.parsers.DocumentBuilder;
importjavax.xml.parsers.DocumentBuilderFactory;
importorg.w3c.dom.Document;
importorg.w3c.dom.Element;
importorg.w3c.dom.Node;
importorg.w3c.dom.NodeList;
publicclassXMLParser{
publicvoidgetAllUserNames(StringfileName){
try{
DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance();
DocumentBuilderdb=dbf.newDocumentBuilder();
Filefile=newFile(fileName);
if(file.exists()){
Documentdoc=db.parse(file);
ElementdocEle=doc.getDocumentElement();
//Printrootelementofthedocument
System.out.println("Rootelementofthedocument:"
+docEle.getNodeName());
NodeListstudentList=docEle.getElementsByTagName("student");
//Printtotalstudentelementsindocument
System.out
.println("Totalstudents:"+studentList.getLength());
if(studentList!=null&&studentList.getLength()>0){
for(inti=0;i<studentList.getLength();i++){
Nodenode=studentList.item(i);
if(node.getNodeType()==Node.ELEMENT_NODE){
System.out
.println("=====================");
Elemente=(Element)node;
NodeListnodeList=e.getElementsByTagName("name");
System.out.println("Name:"
+nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
nodeList=e.getElementsByTagName("grade");
System.out.println("Grade:"
+nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
nodeList=e.getElementsByTagName("age");
System.out.println("Age:"
+nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
}
}
}else{
System.exit(1);
}
}
}catch(Exceptione){
System.out.println(e);
}
}
publicstaticvoidmain(String[]args){
XMLParserparser=newXMLParser();
parser.getAllUserNames("c:\\test.xml");
}
}





20個非常有用的Java程序片段



  • 0.jpg (111.1 KB, 下載次數: 0)


    0.jpg

    0.jpg



  • 0.jpg (111.1 KB, 下載次數: 0)


    0.jpg

    0.jpg


  • 0.jpg (111.1 KB, 下載次數: 0)


    0.jpg

    0.jpg


  • 0.jpg (111.1 KB, 下載次數: 0)


    0.jpg

    0.jpg


  • 0.jpg (111.1 KB, 下載次數: 0)


    0.jpg

    0.jpg


  • 0.jpg (111.1 KB, 下載次數: 0)


    0.jpg

    0.jpg


  • 0.jpg (111.1 KB, 下載次數: 0)


    0.jpg

    0.jpg


  • 0.jpg (111.1 KB, 下載次數: 0)


    0.jpg

    0.jpg


http://www.a5idc.com/thread-142836-1-1.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章