20个开发人员非常有用的Java功能代码

本文将为大家介绍20个对开发人员非常有用的Java功能代码。这20段代码,可以成为大家在今后的开发过程中,Java编程手册的重要部分。

 

1. 把Strings转换成int和把int转换成String

  1. <pre class="java" name="code">
  2. String a = String.valueOf(2);  
  3. //integer to numeric string   
  4. int i = Integer.parseInt(a);  
  5. //numeric string to an int  
  6. String a = String.valueOf(2);  
  7. //integer to numeric string  
  8. int i = Integer.parseInt(a);  
  9. //numeric string to an int</pre></pre> 

2. 向Java文件中添加文本

  1. Updated: Thanks Simone for pointing to exception. I have changed the code.    
  2. BufferedWriter out = null;     
  3. try {     
  4.     out = new BufferedWriter(new FileWriter(”filename”, true));     
  5.     out.write(”aString”);     
  6. catch (IOException e) {     
  7.   
  8. // error processing code     
  9. finally {     
  10.     if (out != null) {  
  11.         out.close();  
  12.     }  
  13. }  
  14.   
  15. BufferedWriter out = null;  
  16. try {  
  17.     out = new BufferedWriter(new FileWriter(”filename”, true));  
  18.     out.write(”aString”);  
  19. catch (IOException e) {  
  20. // error processing code  
  21. finally {  
  22.     if (out != null) {  
  23.         out.close();  
  24.     }  

3. 获取Java现在正调用的方法名

 

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

4. 在Java中将String型转换成Date型

 

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

    OR

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

5. 通过Java JDBC链接Oracle数据库

  1. public class OracleJdbcTest {  
  2.     String driverClass = "oracle.jdbc.driver.OracleDriver";  
  3.     Connection con;  
  4.   
  5.     public void init (FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException {  
  6.         Properties props = new Properties();  
  7.         props.load(fs);  
  8.   
  9.         String url = props.getProperty("db.url");  
  10.         String userName = props.getProperty("db.user");  
  11.   
  12.         String password = props.getProperty("db.password");  
  13.         Class.forName(driverClass);  
  14.   
  15.         con=DriverManager.getConnection(url, userName, password);  
  16.     }  
  17.   
  18.     public void fetch() throws SQLException, IOException {  
  19.   
  20.     PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");  
  21.     ResultSet rs = ps.executeQuery();  
  22.   
  23.     while (rs.next()) {  
  24.         // do the thing you do  
  25.     }  
  26.          
  27.     rs.close();  
  28.     ps.close();  
  29.     }  
  30.   
  31.     public static void main(String[] args) {  
  32.         OracleJdbcTest test = new OracleJdbcTest();  
  33.         test.init();  
  34.         test.fetch();  
  35.     }  
  36. }  
  37.   
  38.   
  39. public class OracleJdbcTest {  
  40.   
  41.     String driverClass = "oracle.jdbc.driver.OracleDriver";  
  42.     Connection con;  
  43.   
  44.     public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException {  
  45.         Properties props = new Properties();  
  46.         props.load(fs);  
  47.         String url = props.getProperty("db.url");  
  48.         String userName = props.getProperty("db.user");  
  49.         String password = props.getProperty("db.password");  
  50.         Class.forName(driverClass);  
  51.         con=DriverManager.getConnection(url, userName, password);  
  52.     }  
  53.   
  54.     public void fetch() throws SQLException, IOException {  
  55.         PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");  
  56.         ResultSet rs = ps.executeQuery();  
  57.   
  58.         while (rs.next()) {  
  59.             // do the thing you do  
  60.         }  
  61.         rs.close();  
  62.         ps.close();  
  63.     }  
  64.   
  65.     public static void main(String[] args) {  
  66.         OracleJdbcTest test = new OracleJdbcTest();  
  67.         test.init();  
  68.         test.fetch();  
  69.     }  
  70. }

6.将Java中的util.Date转换成sql.Date

这一片段显示如何将一个java util Date转换成sql Date用于数据库

 

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

7. 使用NIO快速复制Java文件

  1. public static void fileCopy( File in, File out ) throws IOException {  
  2.     FileChannel inChannel = new FileInputStream( in ).getChannel();  
  3.     FileChannel outChannel = new FileOutputStream( out ).getChannel();  
  4.   
  5.     try {  
  6.         // original -- apparently has trouble copying large files on Windows  
  7.         // magic number for Windows, 64Mb - 32Kb)  
  8.         inChannel.transferTo(0, inChannel.size(), outChannel);  
  9.         int maxCount = (64 * 1024 * 1024) - (32 * 1024);long size = inChannel.size();  
  10.         long position = 0;  
  11.         while (position < size ) {  
  12.             position += inChannel.transferTo( position, maxCount, outChannel );  
  13.         }  
  14.     } finally {  
  15.         if (inChannel != null) {  
  16.             inChannel.close();  
  17.         }  
  18.         if (outChannel != null) {  
  19.             outChannel.close();  
  20.         }  
  21.     }  

8. 在Java中创建缩略图

  1. private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)   
  2.     throws InterruptedException, FileNotFoundException, IOException {  
  3.   
  4.     // load image from filename  
  5.     Image image = Toolkit.getDefaultToolkit().getImage(filename);  
  6.     MediaTracker mediaTracker = new   
  7.     MediaTracker(new Container());  
  8.     mediaTracker.addImage(image, 0);  
  9.     mediaTracker.waitForID(0);  
  10.   
  11.     // use this to test for errors at this point:  
  12.     System.out.println(mediaTracker.isErrorAny());  
  13.   
  14.     // determine thumbnail size from WIDTH and HEIGHT  
  15.     double thumbRatio = (double)thumbWidth / (double)thumbHeight;  
  16.     int imageWidth = image.getWidth(null);  
  17.     int imageHeight = image.getHeight(null);  
  18.     double imageRatio = (double)imageWidth / (double)imageHeight;  
  19.   
  20.     if (thumbRatio < imageRatio) {  
  21.     thumbHeight = (int)(thumbWidth / imageRatio);  
  22.     } else {  
  23.     thumbWidth = (int)(thumbHeight * imageRatio);  
  24.     }  
  25.   
  26.     // draw original image to thumbnail image object and scale it to the new size on-the-fly  
  27.     BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);  
  28.     Graphics2D graphics2D = thumbImage.createGraphics();  
  29.   
  30.     graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);  
  31.     graphics2D.drawImage(image, 00, thumbWidth, thumbHeight, null);  
  32.   
  33.     // save thumbnail image to   
  34.     outFilename BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));  
  35.     JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
  36.     JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);  
  37.     quality = Math.max(0, Math.min(quality, 100));  
  38.     param.setQuality((float)quality / 100.0f, false);  
  39.   
  40.     encoder.setJPEGEncodeParam(param);  
  41.     encoder.encode(thumbImage);  
  42.     out.close();  

9. 在Java中创建JSON数据

  1. Read this article for more details. Download JAR file json-rpc-1.0.jar (75 kb)  
  2.   
  3. import org.json.JSONObject;  
  4. ...  
  5. ...  
  6. JSONObject json = new JSONObject();  
  7.   
  8. json.put("city""Mumbai");  
  9. json.put("country""India");  
  10. ...  
  11. String output = json.toString();  
  12. ...  

10. 在Java中使用iText JAR打开PDF

  1. Read this article for more details.  
  2.   
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.OutputStream;  
  6. import java.util.Date;  
  7. import com.lowagie.text.Document;  
  8. import com.lowagie.text.Paragraph;  
  9. import com.lowagie.text.pdf.PdfWriter;  
  10.   
  11. public class GeneratePDF {  
  12.     public static void main(String[] args) {  
  13.         try {  
  14.             OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));  
  15.             Document document = new Document();  
  16.   
  17.             PdfWriter.getInstance(document, file);  
  18.             document.open();  
  19.             document.add(new Paragraph("Hello Kiran"));  
  20.             document.add(new Paragraph(new Date().toString()));  
  21.             document.close();  
  22.   
  23.             file.close();  
  24.   
  25.         } catch (Exception e) {  
  26.             e.printStackTrace();  
  27.         }  
  28.     }  

11. 在Java上的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. Java Singleton 例子
  1. Read this article for more details.  
  2. Update: Thanks Markus for the comment. I have updated the code and changed it to more robust implementation.  
  3.   
  4. public class SimpleSingleton {  
  5.     private static SimpleSingleton singleInstance =  new SimpleSingleton();  
  6.   
  7.     //Marking default constructor private  
  8.     //to avoid direct instantiation.  
  9.     private SimpleSingleton() {  
  10.     }  
  11.   
  12.     //Get instance for class SimpleSingleton  
  13.     public static SimpleSingleton getInstance() {  
  14.         return singleInstance;  
  15.     }  
  16. }  
  17.   
  18. One more implementation of Singleton class. Thanks to Ralph and Lukasz Zielinski for pointing this out.  
  19.   
  20. public enum SimpleSingleton {  
  21.     INSTANCE;  
  22.     public void doSomething() {  
  23.     }  
  24. }  
  25.   
  26. //Call the method from Singleton:  
  27. SimpleSingleton.INSTANCE.doSomething();  
  28.   
  29. public enum SimpleSingleton {  
  30.     INSTANCE;  
  31.     public void doSomething() {  
  32.     }  

13. 在Java上做屏幕截图

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

14. 在Java中的文件,目录列表

  1. File dir = new File("directoryName");  
  2. String[] children = dir.list();  
  3. if (children == null) {  
  4.     // Either dir does not exist or is not a directory  
  5. else {  
  6.     for (int i=0; i < children.length; i++) {  
  7.         // Get filename of file or directory  
  8.         String filename = children[i];  
  9.     }  
  10. }  
  11.   
  12. // It is also possible to filter the list of returned files.  
  13. // This example does not return any files that start with `.'.  
  14. FilenameFilter filter = new FilenameFilter() {  
  15.     public boolean accept(File dir, String name) {  
  16.         return !name.startsWith(".");  
  17.     }  
  18. };  
  19. children = dir.list(filter);  
  20.   
  21. // The list of files can also be retrieved as File objects  
  22. File[] files = dir.listFiles();  
  23.   
  24. // This filter only returns directories  
  25. FileFilter fileFilter = new FileFilter() {  
  26.     public boolean accept(File file) {  
  27.         return file.isDirectory();  
  28.     }  
  29. };  
  30. files = dir.listFiles(fileFilter);  
15. 在Java中创建ZIP和JAR文件
  1. import java.util.zip.*;  
  2. import java.io.*;  
  3.   
  4. public class ZipIt {  
  5.     public static void main(String args[]) throws IOException {  
  6.         if (args.length < 2) {  
  7.         System.err.println("usage: java ZipIt Zip.zip file1 file2 file3");  
  8.         System.exit(-1);  
  9.         }  
  10.   
  11.         File zipFile = new File(args[0]);  
  12.         if (zipFile.exists()) {  
  13.             System.err.println("Zip file already exists, please try another");  
  14.             System.exit(-2);  
  15.         }  
  16.   
  17.         FileOutputStream fos = new FileOutputStream(zipFile);  
  18.         ZipOutputStream zos = new ZipOutputStream(fos);  
  19.   
  20.         int bytesRead;  
  21.         byte[] buffer = new byte[1024];  
  22.         CRC32 crc = new CRC32();  
  23.         for (int i=1, n=args.length; i < n; i++) {  
  24.             String name = args[i];  
  25.             File file = new File(name);  
  26.   
  27.             if (!file.exists()) {  
  28.                 System.err.println("Skipping: " + name);  
  29.                 continue;  
  30.             }  
  31.   
  32.             BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));  
  33.             crc.reset();  
  34.   
  35.             while ((bytesRead = bis.read(buffer)) != -1) {  
  36.                 crc.update(buffer, 0, bytesRead);     
  37.             }  
  38.             bis.close();  
  39.   
  40.             // Reset to beginning of input stream  
  41.             bis = new BufferedInputStream(new FileInputStream(file));  
  42.             ZipEntry entry = new ZipEntry(name);  
  43.             entry.setMethod(ZipEntry.STORED);  
  44.             entry.setCompressedSize(file.length());  
  45.             entry.setSize(file.length());  
  46.             entry.setCrc(crc.getValue());  
  47.             zos.putNextEntry(entry);  
  48.   
  49.             while ((bytesRead = bis.read(buffer)) != -1) {  
  50.                 zos.write(buffer, 0, bytesRead);  
  51.             }  
  52.             bis.close();  
  53.         }  
  54.         zos.close();  
  55.     }  
  56. }  
16. 在Java中解析/读取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> 

    Java code to parse above XML.

  1. package net.viralpatel.java.xmlparser;  
  2.   
  3. import java.io.File;  
  4. import javax.xml.parsers.DocumentBuilder;  
  5. import javax.xml.parsers.DocumentBuilderFactory;  
  6.   
  7. import org.w3c.dom.Document;  
  8. import org.w3c.dom.Element;  
  9. import org.w3c.dom.Node;  
  10. import org.w3c.dom.NodeList;  
  11.   
  12. public class XMLParser {  
  13.   
  14. public void getAllUserNames(String fileName) {  
  15.     try {  
  16.         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
  17.         DocumentBuilder db = dbf.newDocumentBuilder();  
  18.         File file = new File(fileName);  
  19.         if (file.exists()) {  
  20.             Document doc = db.parse(file);  
  21.             Element docEle = doc.getDocumentElement();  
  22.   
  23.             // Print root element of the document     
  24.             System.out.println("Root element of the document: " + docEle.getNodeName());  
  25.             NodeList studentList = docEle.getElementsByTagName("student");  
  26.   
  27.             // Print total student elements in document  
  28.             System.out.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.                         System.out.println("=====================");  
  37.                         Element e = (Element) node;  
  38.                         NodeList nodeList = e.getElementsByTagName("name");  
  39.                         System.out.println("Name: "  
  40.                         + nodeList.item(0).getChildNodes().item(0).getNodeValue());  
  41.   
  42.                         nodeList = e.getElementsByTagName("grade");  
  43.                         System.out.println("Grade: " + nodeList.item(0).getChildNodes().item(0).getNodeValue());  
  44.   
  45.                         nodeList = e.getElementsByTagName("age");  
  46.                         System.out.println("Age: " + nodeList.item(0).getChildNodes().item(0)  
  47.                         .getNodeValue());  
  48.                     }  
  49.                 }  
  50.             } else {  
  51.                 System.exit(1);  
  52.             }  
  53.         }  
  54.     } catch (Exception e) {  
  55.         ystem.out.println(e);  
  56.     }  
  57. }  
  58.     public static void main(String[] args) {  
  59.         XMLParser parser = new XMLParser();  
  60.         parser.getAllUserNames("c:\\test.xml");  
  61.     }  
  62. }  
17. 在Java中将Array转换成Map
  1. import java.util.Map;  
  2. import org.apache.commons.lang.ArrayUtils;  
  3.   
  4. public class Main {  
  5.     public static void main(String[] args) {  
  6.         String[][] countries = {  
  7.             { "United States""New York" },  
  8.             { "United Kingdom""London" },  
  9.             { "Netherland""Amsterdam" },  
  10.             { "Japan""Tokyo" },  
  11.             { "France""Paris" }  
  12.         };  
  13.   
  14.         Map countryCapitals = ArrayUtils.toMap(countries);  
  15.   
  16.         System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));  
  17.         System.out.println("Capital of France is " + countryCapitals.get("France"));  
  18.     }  

18. 在Java中发送电子邮件

  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.     boolean debug = false;  
  7.   
  8.     //Set the host smtp address  
  9.     Properties props = new Properties();  
  10.     props.put("mail.smtp.host""smtp.example.com");  
  11.   
  12.     // create some properties and get the default Session  
  13.     Session session = Session.getDefaultInstance(props, null);  
  14.     session.setDebug(debug);  
  15.   
  16.     // create a message  
  17.     Message msg = new MimeMessage(session);  
  18.   
  19.     // set the from and to address  
  20.     InternetAddress addressFrom = new InternetAddress(from);  
  21.     msg.setFrom(addressFrom);  
  22.   
  23.     InternetAddress[] addressTo = new InternetAddress[recipients.length];  
  24.     for (int i = 0; i < recipients.length; i++) {  
  25.         addressTo[i] = new InternetAddress(recipients[i]);  
  26.     }  
  27.     msg.setRecipients(Message.RecipientType.TO, addressTo);  
  28.   
  29.     // Optional : You can also set your custom headers in the Email if you Want  
  30.     msg.addHeader("MyHeaderName""myHeaderValue");  
  31.   
  32.     // Setting the Subject and Content Type  
  33.     msg.setSubject(subject);  
  34.     msg.setContent(message, "text/plain");  
  35.     Transport.send(msg);  
  36. }  
19. 使用Java发送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://www.viralpatel.net/blogs/");  
  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.     }  
  18. }  

20. 在Java中调整数组

  1. /** 
  2.  *  Reallocates an array with a new size, and 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. **/  
  8. private static Object resizeArray (Object oldArray, int newSize) {  
  9.     int oldSize = java.lang.reflect.Array.getLength(oldArray);  
  10.     Class elementType = oldArray.getClass().getComponentType();  
  11.     Object newArray = java.lang.reflect.Array.newInstance(elementType,newSize);  
  12.     int preserveLength = Math.min(oldSize,newSize);  
  13.     if (preserveLength > 0)  
  14.         System.arraycopy (oldArray,0,newArray,0,preserveLength);  
  15.           
  16.     return newArray;  
  17. }  
  18.   
  19. // Test routine for resizeArray().  
  20. public static void main (String[] args) {  
  21.     int[] a = {1,2,3};  
  22.     a = (int[])resizeArray(a,5);  
  23.     a[3] = 4;  
  24.     a[4] = 5;  
  25.     for (int i=0; i<a.length; i++)  
  26.         System.out.println (a[i]);  
  27. }  


 

posted @ 2017-03-12 23:11  星朝  阅读(1350)  评论(0编辑  收藏  举报