天天看点

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

下面是20个非常有用的java程序片段,希望能对你有用。内容比较早,有些函数可能过时了,但是总体思路是不错滴,供参考。

1、字符串有整型的相互转换

string a = string.valueof(2);   //integer to numeric string 

int i = integer.parseint(a); //numeric string to an int 

2、向文件末尾添加内容

bufferedwriter out = null;      

try {      

    out = new bufferedwriter(new filewriter(”filename”, true));      

    out.write(”astring”);      

} catch (ioexception e) {      

    // error processing code      

} finally {      

    if (out != null) {      

        out.close();      

    }      

}  

3、得到当前方法的名字

string methodname = thread.currentthread().getstacktrace()[1].getmethodname(); 

4、转字符串到日期

java.util.date = java.text.dateformat.getdateinstance().parse(date string); 

或者是:

simpledateformat format = new simpledateformat( "dd.mm.yyyy" ); 

date date = format.parse( mystring );  

5、使用jdbc链接oracle

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

6、把 java util.date 转成 sql.date

java.util.date utildate = new java.util.date(); 

java.sql.date sqldate = new java.sql.date(utildate.gettime());  

7、使用nio进行快速的文件拷贝

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

8、创建图片的缩略图

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

9、创建 json 格式的数据

请先阅读这篇文章 了解一些细节,

并下面这个jar 文件:json-rpc-1.0.jar (75 kb) http://viralpatel.net/blogs/download/json/json-rpc-1.0.jar

import org.json.jsonobject;      

...      

...   

jsonobject json = new jsonobject();   

json.put("city", "mumbai");   

json.put("country", "india");      

string output = json.tostring();      

...  

10、使用itext jar生成pdf

阅读这篇文章 了解更多细节

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

11、http 代理设置

阅读这篇 文章 了解更多细节。

system.getproperties().put("http.proxyhost", "someproxyurl");   

system.getproperties().put("http.proxyport", "someproxyport");   

system.getproperties().put("http.proxyuser", "someusername");   

system.getproperties().put("http.proxypassword", "somepassword");  

12、单实例singleton 示例

请先阅读这篇文章 了解更多信息

public class simplesingleton {      

    private static simplesingleton singleinstance =  new simplesingleton();      

    //marking default constructor private      

    //to avoid direct instantiation.      

    private simplesingleton() {      

    //get instance for class simplesingleton      

    public static simplesingleton getinstance() {      

        return singleinstance;      

另一种实现

public enum simplesingleton {      

    instance;      

    public void dosomething() {      

}      

//call the method from singleton:  simplesingleton.instance.dosomething();  

13、抓屏程序

阅读这篇文章 获得更多信息。

import java.awt.dimension;   

import java.awt.rectangle;   

import java.awt.robot;   

import java.awt.toolkit;   

import java.awt.image.bufferedimage;   

import javax.imageio.imageio;  import java.io.file;    

public void capturescreen(string filename) throws exception {      

   dimension screensize = toolkit.getdefaulttoolkit().getscreensize();      

   rectangle screenrectangle = new rectangle(screensize);      

   robot robot = new robot();      

   bufferedimage image = robot.createscreencapture(screenrectangle);      

   imageio.write(image, "png", new file(filename));      

14、列出文件和目录 

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

15、创建zip和jar文件

import java.util.zip.*;  import java.io.*;      

public class zipit {      

    public static void main(string args[]) throws ioexception {      

        if (args.length < 2) {      

            system.err.println("usage: java zipit zip.zip file1 file2 file3");      

            system.exit(-1);      

        }      

        file zipfile = new file(args[0]);      

        if (zipfile.exists()) {      

            system.err.println("zip file already exists, please try another");      

            system.exit(-2);      

        fileoutputstream fos = new fileoutputstream(zipfile);      

        zipoutputstream zos = new zipoutputstream(fos);      

        int bytesread;      

        byte[] buffer = new byte[1024];      

        crc32 crc = new crc32();      

        for (int i=1, n=args.length; i < n; i++) {      

            string name = args[i];      

            file file = new file(name);      

            if (!file.exists()) {      

                system.err.println("skipping: " + name);      

                continue;      

            }      

            bufferedinputstream bis = new bufferedinputstream(      

                new fileinputstream(file));      

            crc.reset();      

            while ((bytesread = bis.read(buffer)) != -1) {      

                crc.update(buffer, 0, bytesread);      

            bis.close();      

            // reset to beginning of input stream      

            bis = new bufferedinputstream(      

            zipentry entry = new zipentry(name);      

            entry.setmethod(zipentry.stored);      

            entry.setcompressedsize(file.length());      

            entry.setsize(file.length());      

            entry.setcrc(crc.getvalue());      

            zos.putnextentry(entry);      

                zos.write(buffer, 0, bytesread);      

        zos.close();      

16、解析/读取xml 文件

<?xml version="1.0"?>     

<students>     

    <student>     

        <name>john</name>     

        <grade>b</grade>     

        <age>12</age>     

    </student>     

        <name>mary</name>     

        <grade>a</grade>     

        <age>11</age>     

    <student>    

        <name>simon</name>     

        <age>18</age>     

</students>  

xml文件

java代码

package net.viralpatel.java.xmlparser;      

import java.io.file;   

import javax.xml.parsers.documentbuilder;   

import javax.xml.parsers.documentbuilderfactory;      

import org.w3c.dom.document;   

import org.w3c.dom.element;   

import org.w3c.dom.node;   

import org.w3c.dom.nodelist;      

public class xmlparser {      

    public void getallusernames(string filename) {      

        try {      

            documentbuilderfactory dbf = documentbuilderfactory.newinstance();      

            documentbuilder db = dbf.newdocumentbuilder();      

            file file = new file(filename);      

            if (file.exists()) {      

                document doc = db.parse(file);      

                element docele = doc.getdocumentelement();      

                // print root element of the document      

                system.out.println("root element of the document: "     

                        + docele.getnodename());      

                nodelist studentlist = docele.getelementsbytagname("student");      

                // print total student elements in document      

                system.out      

                        .println("total students: " + studentlist.getlength());      

                if (studentlist != null && studentlist.getlength() > 0) {      

                    for (int i = 0; i < studentlist.getlength(); i++) {      

                        node node = studentlist.item(i);      

                        if (node.getnodetype() == node.element_node) {      

                            system.out      

                                    .println("=====================");      

                            element e = (element) node;      

                            nodelist nodelist = e.getelementsbytagname("name");      

                            system.out.println("name: "     

                                    + nodelist.item(0).getchildnodes().item(0)      

                                            .getnodevalue());      

                            nodelist = e.getelementsbytagname("grade");      

                            system.out.println("grade: "     

                            nodelist = e.getelementsbytagname("age");      

                            system.out.println("age: "     

                        }      

                    }      

                } else {      

                    system.exit(1);      

                }      

        } catch (exception e) {      

            system.out.println(e);      

    public static void main(string[] args) {      

        xmlparser parser = new xmlparser();      

        parser.getallusernames("c:\\test.xml");      

17、把 array 转换成 map

import java.util.map;   

import org.apache.commons.lang.arrayutils;      

public class main {      

  public static void main(string[] args) {      

    string[][] countries = { { "united states", "new york" }, { "united kingdom", "london" },      

        { "netherland", "amsterdam" }, { "japan", "tokyo" }, { "france", "paris" } };      

    map countrycapitals = arrayutils.tomap(countries);      

    system.out.println("capital of japan is " + countrycapitals.get("japan"));      

    system.out.println("capital of france is " + countrycapitals.get("france"));      

  }      

18、发送邮件

import javax.mail.*;   

import javax.mail.internet.*;   

import java.util.*;      

public void postmail( string recipients[ ], string subject, string message , string from) throws messagingexception      

{      

    boolean debug = false;      

     //set the host smtp address      

     properties props = new properties();      

     props.put("mail.smtp.host", "smtp.example.com");      

    // create some properties and get the default session      

    session session = session.getdefaultinstance(props, null);      

    session.setdebug(debug);      

    // create a message      

    message msg = new mimemessage(session);      

    // set the from and to address      

    internetaddress addressfrom = new internetaddress(from);      

    msg.setfrom(addressfrom);      

    internetaddress[] addressto = new internetaddress[recipients.length];      

    for (int i = 0; i < recipients.length; i++)      

    {      

        addressto[i] = new internetaddress(recipients[i]);      

    msg.setrecipients(message.recipienttype.to, addressto);      

    // optional : you can also set your custom headers in the email if you want      

    msg.addheader("myheadername", "myheadervalue");      

    // setting the subject and content type      

    msg.setsubject(subject);      

    msg.setcontent(message, "text/plain");      

    transport.send(msg);      

19、发送代数据的http 请求

import java.io.bufferedreader;   

import java.io.inputstreamreader;   

import java.net.url;      

    public static void main(string[] args)  {      

            url my_url = new url("http://coolshell.cn/");      

            bufferedreader br = new bufferedreader(new inputstreamreader(my_url.openstream()));      

            string strtemp = "";      

            while(null != (strtemp = br.readline())){      

            system.out.println(strtemp);      

        } catch (exception ex) {      

            ex.printstacktrace();      

    }   

20、改变数组的大小   

/**  

* reallocates an array with a new size, and copies the contents     

* of the old array to the new array.     

* @param oldarray  the old array, to be reallocated.     

* @param newsize   the new array size.     

* @return          a new array with the same contents.     

*/ private static object resizearray (object oldarray, int newsize) {      

   int oldsize = java.lang.reflect.array.getlength(oldarray);      

   class elementtype = oldarray.getclass().getcomponenttype();      

   object newarray = java.lang.reflect.array.newinstance(      

         elementtype,newsize);      

   int preservelength = math.min(oldsize,newsize);      

   if (preservelength > 0)      

      system.arraycopy (oldarray,0,newarray,0,preservelength);      

   return newarray;      

// test routine for resizearray().public static void main (string[] args) {      

   int[] a = {1,2,3};      

   a = (int[])resizearray(a,5);      

   a[3] = 4;      

   a[4] = 5;      

   for (int i=0; i<a.length; i++)      

      system.out.println (a[i]);      

plain  

作者:陈皓

来源:51cto