欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java中常用的代码汇总

程序员文章站 2024-03-03 15:22:34
1. 字符串有整型的相互转换 string a = string.valueof(2);   //integer to numeric strin...

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

public class oraclejdbctest 
{ 
  string driverclass = "oracle.jdbc.driver.oracledriver"; 
  
  connection con; 
  
  public void init(fileinputstream fs) throws classnotfoundexception, sqlexception, filenotfoundexception, ioexception 
  { 
    properties props = new properties(); 
    props.load(fs); 
    string url = props.getproperty("db.url"); 
    string username = props.getproperty("db.user"); 
    string password = props.getproperty("db.password"); 
    class.forname(driverclass); 
  
    con=drivermanager.getconnection(url, username, password); 
  } 
  
  public void fetch() throws sqlexception, ioexception 
  { 
    preparedstatement ps = con.preparestatement("select sysdate from dual"); 
    resultset rs = ps.executequery(); 
  
    while (rs.next()) 
    { 
      // do the thing you do 
    } 
    rs.close(); 
    ps.close(); 
  } 
  
  public static void main(string[] args) 
  { 
    oraclejdbctest test = new oraclejdbctest(); 
    test.init(); 
    test.fetch(); 
  } 
}

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进行快速的文件拷贝

public static void filecopy( file in, file out ) 
      throws ioexception 
  { 
    filechannel inchannel = new fileinputstream( in ).getchannel(); 
    filechannel outchannel = new fileoutputstream( out ).getchannel(); 
    try
    { 
//     inchannel.transferto(0, inchannel.size(), outchannel);   // original -- apparently has trouble copying large files on windows 
  
      // magic number for windows, 64mb - 32kb) 
      int maxcount = (64 * 1024 * 1024) - (32 * 1024); 
      long size = inchannel.size(); 
      long position = 0; 
      while ( position < size ) 
      { 
        position += inchannel.transferto( position, maxcount, outchannel ); 
      } 
    } 
    finally
    { 
      if ( inchannel != null ) 
      { 
        inchannel.close(); 
      } 
      if ( outchannel != null ) 
      { 
        outchannel.close(); 
      } 
    } 
  }

8. 创建图片的缩略图

private void createthumbnail(string filename, int thumbwidth, int thumbheight, int quality, string outfilename) 
    throws interruptedexception, filenotfoundexception, ioexception 
  { 
    // load image from filename 
    image image = toolkit.getdefaulttoolkit().getimage(filename); 
    mediatracker mediatracker = new mediatracker(new container()); 
    mediatracker.addimage(image, 0); 
    mediatracker.waitforid(0); 
    // use this to test for errors at this point: system.out.println(mediatracker.iserrorany()); 
  
    // determine thumbnail size from width and height 
    double thumbratio = (double)thumbwidth / (double)thumbheight; 
    int imagewidth = image.getwidth(null); 
    int imageheight = image.getheight(null); 
    double imageratio = (double)imagewidth / (double)imageheight; 
    if (thumbratio < imageratio) { 
      thumbheight = (int)(thumbwidth / imageratio); 
    } else { 
      thumbwidth = (int)(thumbheight * imageratio); 
    } 
  
    // draw original image to thumbnail image object and 
    // scale it to the new size on-the-fly 
    bufferedimage thumbimage = new bufferedimage(thumbwidth, thumbheight, bufferedimage.type_int_rgb); 
    graphics2d graphics2d = thumbimage.creategraphics(); 
    graphics2d.setrenderinghint(renderinghints.key_interpolation, renderinghints.value_interpolation_bilinear); 
    graphics2d.drawimage(image, 0, 0, thumbwidth, thumbheight, null); 
  
    // save thumbnail image to outfilename 
    bufferedoutputstream out = new bufferedoutputstream(new fileoutputstream(outfilename)); 
    jpegimageencoder encoder = jpegcodec.createjpegencoder(out); 
    jpegencodeparam param = encoder.getdefaultjpegencodeparam(thumbimage); 
    quality = math.max(0, math.min(quality, 100)); 
    param.setquality((float)quality / 100.0f, false); 
    encoder.setjpegencodeparam(param); 
    encoder.encode(thumbimage); 
    out.close(); 
  }

9.创建 json 格式的数据

并下面这个jar 文件:json-rpc-1.0.jar (75 kb)/http://t.cn/rz0bhua

import org.json.jsonobject; 
... 
... 
jsonobject json = new jsonobject(); 
json.put("city", "mumbai"); 
json.put("country", "india"); 
... 
string output = json.tostring(); 
...

10. 使用itext jar生成pdf

import java.io.file; 
import java.io.fileoutputstream; 
import java.io.outputstream; 
import java.util.date; 
  
import com.lowagie.text.document; 
import com.lowagie.text.paragraph; 
import com.lowagie.text.pdf.pdfwriter; 
  
public class generatepdf { 
  
  public static void main(string[] args) { 
    try { 
      outputstream file = new fileoutputstream(new file("c:\\test.pdf")); 
  
      document document = new document(); 
      pdfwriter.getinstance(document, file); 
      document.open(); 
      document.add(new paragraph("hello kiran")); 
      document.add(new paragraph(new date().tostring())); 
  
      document.close(); 
      file.close(); 
  
    } catch (exception e) { 
  
      e.printstacktrace(); 
    } 
  } 
}

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; 
  } 
}

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. 列出文件和目录

file dir = new file("directoryname"); 
 string[] children = dir.list(); 
 if (children == null) { 
   // either dir does not exist or is not a directory 
 } else { 
   for (int i=0; i < children.length; i++) { 
     // get filename of file or directory 
     string filename = children[i]; 
   } 
 } 
  
 // it is also possible to filter the list of returned files. 
 // this example does not return any files that start with `.'. 
 filenamefilter filter = new filenamefilter() { 
   public boolean accept(file dir, string name) { 
     return !name.startswith("."); 
   } 
 }; 
 children = dir.list(filter); 
  
 // the list of files can also be retrieved as file objects 
 file[] files = dir.listfiles(); 
  
 // this filter only returns directories 
 filefilter filefilter = new filefilter() { 
   public boolean accept(file file) { 
     return file.isdirectory(); 
   } 
 }; 
 files = dir.listfiles(filefilter);

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( 
        new fileinputstream(file)); 
      zipentry entry = new zipentry(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文件

<?xml version="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代码

<span style="font-family:arial;font-size:14px;">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.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 (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 class main { 
  public static void main(string[] args) { 
    try { 
      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]); 
}

以上所述就是本文的全部内容了,希望大家能够喜欢。