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

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

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

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

  1. String a = String.valueOf(2);   //integer to numeric string 
  2. int i = Integer.parseInt(a); //numeric string to an int 

2、向文件末尾添加内容

  1. BufferedWriter out = null;      
  2. try {      
  3.     out = new BufferedWriter(new FileWriter(”filename”, true));      
  4.     out.write(”aString”);      
  5. } catch (IOException e) {      
  6.     // error processing code      
  7. } finally {      
  8.     if (out != null) {      
  9.         out.close();      
  10.     }      
  11.  

3、得到当前方法的名字

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

4、转字符串到日期

  1. java.util.Date = java.text.DateFormat.getDateInstance().parse(date String); 

或者是:

  1. SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" ); 
  2.  
  3. Date date = format.parse( myString );  

5、使用JDBC链接Oracle

    

 

6、把 Java util.Date 转成 sql.Date

  1. java.util.Date utilDate = new java.util.Date(); 
  2.  
  3. java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());  

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

 

8、创建图片的缩略图 

 

 

9、创建 JSON 格式的数据

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

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

  1. import org.json.JSONObject;      
  2. ...      
  3. ...   
  4. JSONObject json = new JSONObject();   
  5. json.put("city""Mumbai");   
  6. json.put("country""India");      
  7. ...   
  8. String output = json.toString();      
  9. ...  

10、使用iText JAR生成PDF

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

 

11、HTTP 代理设置

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

  1. System.getProperties().put("http.proxyHost""someProxyURL");   
  2. System.getProperties().put("http.proxyPort""someProxyPort");   
  3. System.getProperties().put("http.proxyUser""someUserName");   
  4. System.getProperties().put("http.proxyPassword""somePassword");  

12、单实例Singleton 示例

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

  1. public class SimpleSingleton {      
  2.     private static SimpleSingleton singleInstance =  new SimpleSingleton();      
  3.  
  4.     //Marking default constructor private      
  5.     //to avoid direct instantiation.      
  6.     private SimpleSingleton() {      
  7.     }      
  8.  
  9.     //Get instance for class SimpleSingleton      
  10.     public static SimpleSingleton getInstance() {      
  11.  
  12.         return singleInstance;      
  13.     }      

另一种实现

  1. public enum SimpleSingleton {      
  2.     INSTANCE;      
  3.     public void doSomething() {      
  4.     }      
  5. }      
  6. //Call the method from Singleton:  SimpleSingleton.INSTANCE.doSomething();  

13、抓屏程序

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

  1. import java.awt.Dimension;   
  2. import java.awt.Rectangle;   
  3. import java.awt.Robot;   
  4. import java.awt.Toolkit;   
  5. import java.awt.image.BufferedImage;   
  6. import javax.imageio.ImageIO;  import java.io.File;    
  7. ...      
  8. public void captureScreen(String fileName) throws Exception {      
  9.  
  10.    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();      
  11.    Rectangle screenRectangle = new Rectangle(screenSize);      
  12.    Robot robot = new Robot();      
  13.    BufferedImage image = robot.createScreenCapture(screenRectangle);      
  14.    ImageIO.write(image, "png", new File(fileName));      
  15.  
  16. }      
  17. ...  

14、列出文件和目录 

 

15、创建ZIP和JAR文件

  1. import java.util.zip.*;  import java.io.*;      
  2.  
  3. public class ZipIt {      
  4.     public static void main(String args[]) throws IOException {      
  5.         if (args.length < 2) {      
  6.             System.err.println("usage: java ZipIt Zip.zip file1 file2 file3");      
  7.             System.exit(-1);      
  8.         }      
  9.         File zipFile = new File(args[0]);      
  10.         if (zipFile.exists()) {      
  11.             System.err.println("Zip file already exists, please try another");      
  12.             System.exit(-2);      
  13.         }      
  14.         FileOutputStream fos = new FileOutputStream(zipFile);      
  15.         ZipOutputStream zos = new ZipOutputStream(fos);      
  16.         int bytesRead;      
  17.         byte[] buffer = new byte[1024];      
  18.         CRC32 crc = new CRC32();      
  19.         for (int i=1, n=args.length; i < n; i++) {      
  20.             String name = args[i];      
  21.             File file = new File(name);      
  22.             if (!file.exists()) {      
  23.                 System.err.println("Skipping: " + name);      
  24.                 continue;      
  25.             }      
  26.             BufferedInputStream bis = new BufferedInputStream(      
  27.                 new FileInputStream(file));      
  28.             crc.reset();      
  29.             while ((bytesRead = bis.read(buffer)) != -1) {      
  30.                 crc.update(buffer, 0, bytesRead);      
  31.             }      
  32.             bis.close();      
  33.             // Reset to beginning of input stream      
  34.             bis = new BufferedInputStream(      
  35.                 new FileInputStream(file));      
  36.             ZipEntry entry = new ZipEntry(name);      
  37.             entry.setMethod(ZipEntry.STORED);      
  38.             entry.setCompressedSize(file.length());      
  39.             entry.setSize(file.length());      
  40.             entry.setCrc(crc.getValue());      
  41.             zos.putNextEntry(entry);      
  42.             while ((bytesRead = bis.read(buffer)) != -1) {      
  43.                 zos.write(buffer, 0, bytesRead);      
  44.             }      
  45.             bis.close();      
  46.         }      
  47.         zos.close();      
  48.     }      
  49.  

16、解析/读取XML 文件

  1. <?xml version="1.0"?>     
  2. <students>     
  3.     <student>     
  4.         <name>John</name>     
  5.         <grade>B</grade>     
  6.         <age>12</age>     
  7.     </student>     
  8.     <student>     
  9.         <name>Mary</name>     
  10.         <grade>A</grade>     
  11.         <age>11</age>     
  12.     </student>     
  13.     <student>    
  14.         <name>Simon</name>     
  15.         <grade>A</grade>     
  16.         <age>18</age>     
  17.     </student>     
  18. </students>  

XML文件

Java代码

  1. package net.viralpatel.java.xmlparser;      
  2. import java.io.File;   
  3. import javax.xml.parsers.DocumentBuilder;   
  4. import javax.xml.parsers.DocumentBuilderFactory;      
  5. import org.w3c.dom.Document;   
  6. import org.w3c.dom.Element;   
  7. import org.w3c.dom.Node;   
  8. import org.w3c.dom.NodeList;      
  9. public class XMLParser {      
  10.  
  11.     public void getAllUserNames(String fileName) {      
  12.         try {      
  13.             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();      
  14.             DocumentBuilder db = dbf.newDocumentBuilder();      
  15.             File file = new File(fileName);      
  16.             if (file.exists()) {      
  17.                 Document doc = db.parse(file);      
  18.                 Element docEle = doc.getDocumentElement();      
  19.  
  20.                 // Print root element of the document      
  21.                 System.out.println("Root element of the document: "     
  22.                         + docEle.getNodeName());      
  23.  
  24.                 NodeList studentList = docEle.getElementsByTagName("student");      
  25.  
  26.                 // Print total student elements in document      
  27.                 System.out      
  28.                         .println("Total students: " + studentList.getLength());      
  29.  
  30.                 if (studentList != null && studentList.getLength() > 0) {      
  31.                     for (int i = 0; i < studentList.getLength(); i++) {      
  32.  
  33.                         Node node = studentList.item(i);      
  34.  
  35.                         if (node.getNodeType() == Node.ELEMENT_NODE) {      
  36.  
  37.                             System.out      
  38.                                     .println("=====================");      
  39.  
  40.                             Element e = (Element) node;      
  41.                             NodeList nodeList = e.getElementsByTagName("name");      
  42.                             System.out.println("Name: "     
  43.                                     + nodeList.item(0).getChildNodes().item(0)      
  44.                                             .getNodeValue());      
  45.  
  46.                             nodeList = e.getElementsByTagName("grade");      
  47.                             System.out.println("Grade: "     
  48.                                     + nodeList.item(0).getChildNodes().item(0)      
  49.                                             .getNodeValue());      
  50.  
  51.                             nodeList = e.getElementsByTagName("age");      
  52.                             System.out.println("Age: "     
  53.                                     + nodeList.item(0).getChildNodes().item(0)      
  54.                                             .getNodeValue());      
  55.                         }      
  56.                     }      
  57.                 } else {      
  58.                     System.exit(1);      
  59.                 }      
  60.             }      
  61.         } catch (Exception e) {      
  62.             System.out.println(e);      
  63.         }      
  64.     }      
  65.     public static void main(String[] args) {      
  66.  
  67.         XMLParser parser = new XMLParser();      
  68.         parser.getAllUserNames("c:\\test.xml");      
  69.     }      
  70.  

17、把 Array 转换成 Map

  1. import java.util.Map;   
  2. import org.apache.commons.lang.ArrayUtils;      
  3.  
  4. public class Main {      
  5.  
  6.   public static void main(String[] args) {      
  7.     String[][] countries = { { "United States""New York" }, { "United Kingdom""London" },      
  8.         { "Netherland""Amsterdam" }, { "Japan""Tokyo" }, { "France""Paris" } };      
  9.  
  10.     Map countryCapitals = ArrayUtils.toMap(countries);      
  11.  
  12.     System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));      
  13.     System.out.println("Capital of France is " + countryCapitals.get("France"));      
  14.   }      
  15.  

18、发送邮件

  1. import javax.mail.*;   
  2. import javax.mail.internet.*;   
  3. import java.util.*;      
  4.  
  5. public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException      
  6. {      
  7.     boolean debug = false;      
  8.  
  9.      //Set the host smtp address      
  10.      Properties props = new Properties();      
  11.      props.put("mail.smtp.host""smtp.example.com");      
  12.  
  13.     // create some properties and get the default Session      
  14.     Session session = Session.getDefaultInstance(props, null);      
  15.     session.setDebug(debug);      
  16.  
  17.     // create a message      
  18.     Message msg = new MimeMessage(session);      
  19.  
  20.     // set the from and to address      
  21.     InternetAddress addressFrom = new InternetAddress(from);      
  22.     msg.setFrom(addressFrom);      
  23.  
  24.     InternetAddress[] addressTo = new InternetAddress[recipients.length];      
  25.     for (int i = 0; i < recipients.length; i++)      
  26.     {      
  27.         addressTo[i] = new InternetAddress(recipients[i]);      
  28.     }      
  29.     msg.setRecipients(Message.RecipientType.TO, addressTo);      
  30.  
  31.     // Optional : You can also set your custom headers in the Email if you Want      
  32.     msg.addHeader("MyHeaderName""myHeaderValue");      
  33.  
  34.     // Setting the Subject and Content Type      
  35.     msg.setSubject(subject);      
  36.     msg.setContent(message, "text/plain");      
  37.     Transport.send(msg);      
  38.  

19、发送代数据的HTTP 请求

  1. import java.io.BufferedReader;   
  2. import java.io.InputStreamReader;   
  3. import java.net.URL;      
  4.  
  5. public class Main {      
  6.     public static void main(String[] args)  {      
  7.         try {      
  8.             URL my_url = new URL("http://coolshell.cn/");      
  9.             BufferedReader br = new BufferedReader(new InputStreamReader(my_url.openStream()));      
  10.             String strTemp = "";      
  11.             while(null != (strTemp = br.readLine())){      
  12.             System.out.println(strTemp);      
  13.         }      
  14.         } catch (Exception ex) {      
  15.             ex.printStackTrace();      
  16.         }      
  17.     }   

20、改变数组的大小   

  1. /**  
  2. * Reallocates an array with a new sizeand copies the contents     
  3. of the old array to the new array.     
  4. * @param oldArray  the old array, to be reallocated.     
  5. * @param newSize   the new array size.     
  6. * @return          A new array with the same contents.     
  7. */ private static Object resizeArray (Object oldArray, int newSize) {      
  8.    int oldSize = java.lang.reflect.Array.getLength(oldArray);      
  9.    Class elementType = oldArray.getClass().getComponentType();      
  10.    Object newArray = java.lang.reflect.Array.newInstance(      
  11.          elementType,newSize);      
  12.    int preserveLength = Math.min(oldSize,newSize);      
  13.    if (preserveLength > 0)      
  14.       System.arraycopy (oldArray,0,newArray,0,preserveLength);      
  15.    return newArray;      
  16. }      
  17.  
  18. // Test routine for resizeArray().public static void main (String[] args) {      
  19.    int[] a = {1,2,3};      
  20.    a = (int[])resizeArray(a,5);      
  21.    a[3] = 4;      
  22.    a[4] = 5;      
  23.    for (int i=0; i<a.length; i++)      
  24.       System.out.println (a[i]);      
  25. plain  
责任编辑:庞桂玉 来源: 程序猿
相关推荐

2013-06-14 14:57:09

Java基础代码

2017-11-16 08:15:26

程序员Java程序

2023-06-13 15:15:02

JavaScript前端编程语言

2009-03-24 14:23:59

PHP类库PHP开发PHP

2022-06-27 19:01:04

Python应用程序数据

2018-08-03 10:02:05

Linux命令

2013-08-12 15:00:24

LinuxLinux命令

2013-08-13 10:46:51

LinuxLinux命令

2009-05-18 16:58:56

Java代码片段

2021-10-21 22:03:00

PythonNumpy函数

2020-10-29 10:00:55

Python函数文件

2011-07-07 17:16:43

PHP

2023-02-19 15:22:22

React技巧

2022-09-02 23:08:04

JavaScript技巧开发

2013-11-05 10:03:22

Eclipse功能

2013-08-21 10:31:22

HTML5工具

2021-03-09 09:14:27

ES2019JavaScript开发

2009-02-09 11:20:06

Windows7Windows

2015-08-12 11:09:42

开发者设计原则

2014-09-18 09:50:32

Ruby on Rai
点赞
收藏

51CTO技术栈公众号