Java常用功能代码

1. 屏幕截图

Java代码  收藏代码

  1. public static void main(String[] args)throws Exception {  

  2.     String filename = "d:\\Temp\\screen.png";  

  3.     // 获取屏幕尺寸  

  4.     Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();  

  5.     Rectangle rectangle = new Rectangle(dimension);  

  6.     // 创建图像  

  7.     BufferedImage image = new Robot().createScreenCapture(rectangle);  

  8.     // 保存到磁盘   

  9.     // @see ImageIO#getWriterFormatNames();  

  10.     ImageIO.write(image, "png", new File(filename));  

  11. }  

2. 缩放图像

Java代码  收藏代码

  1. package org.demo.common;  

  2.   

  3. import java.awt.Container;  

  4. import java.awt.Graphics2D;  

  5. import java.awt.Image;  

  6. import java.awt.MediaTracker;  

  7. import java.awt.RenderingHints;  

  8. import java.awt.Toolkit;  

  9. import java.awt.image.BufferedImage;  

  10. import java.io.BufferedOutputStream;  

  11. import java.io.FileOutputStream;  

  12. import java.io.IOException;  

  13.   

  14. import com.sun.image.codec.jpeg.JPEGCodec;  

  15. import com.sun.image.codec.jpeg.JPEGEncodeParam;  

  16. import com.sun.image.codec.jpeg.JPEGImageEncoder;  

  17.   

  18. /** 

  19.  * 创建缩略图 

  20.  * @author   

  21.  * @date    2010-6-19 

  22.  * @file    org.demo.common.ImageThumbnail.java 

  23.  */  

  24. public class ImageThumbnail {  

  25.   

  26.     /** 

  27.      * @param args 

  28.      */  

  29.     public static void main(String[] args)throws Exception {  

  30.         String inFilename = "d:\\Temp\\demo1.png";  

  31.         String outFilename = "d:\\Temp\\demo2.png";  

  32.         createThumbnail(inFilename, outFilename, 800, 600, 0.75f);  

  33.     }  

  34.     /** 

  35.      * 创建缩略图 

  36.      * @param inFilename 

  37.      * @param outFilename     

  38.      * @param thumbWidth 

  39.      * @param thumbHeight 

  40.      * @param quality 

  41.      *        [0.0,1.0] 

  42.      * @return 

  43.      */  

  44.     public static void createThumbnail(  

  45.             String inFilename,String outFilename,  

  46.             int thumbWidth,int thumbHeight,float quality)  

  47.             throws IOException,InterruptedException{  

  48.         // 加载图像  

  49.         Image image = Toolkit.getDefaultToolkit().getImage(inFilename);  

  50.         // 创建图像追踪器  

  51.         MediaTracker mediaTracker = new MediaTracker(new Container());  

  52.         mediaTracker.addImage(image, 0);  

  53.         /** !必须等图像完全加载到内存之后才能执行后续操作! */  

  54.         mediaTracker.waitForID(0);  

  55.         System.out.println("isErrorAny=" + mediaTracker.isErrorAny());  

  56.         // 计算等比例缩放的实际 宽高值  

  57.         double thumbRatio = thumbWidth/thumbHeight;  

  58.         int imageWidth = image.getWidth(null);  

  59.         int imageHeight = image.getHeight(null);  

  60.         double imageRatio = (double)imageWidth/imageHeight;  

  61.         if (thumbRatio < imageRatio){  

  62.             // --> height  

  63.             thumbHeight = (int)(thumbWidth/imageRatio);  

  64.         } else {  

  65.             // --> width  

  66.             thumbWidth = (int)(thumbHeight * imageRatio);  

  67.         }  

  68.         // 创建内存缩略图  

  69.         BufferedImage bufferedImage = new BufferedImage(thumbWidth,   

  70.                                                         thumbHeight,   

  71.                                                         BufferedImage.TYPE_INT_RGB);  

  72.         Graphics2D g2d = bufferedImage.createGraphics();  

  73.         g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,  

  74.                              RenderingHints.VALUE_INTERPOLATION_BILINEAR);  

  75.         g2d.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);  

  76.         // 将内存缩略图 写入 文件  

  77.         BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));  

  78.         JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  

  79.         JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);  

  80.         param.setQuality(quality,false);  

  81.         encoder.setJPEGEncodeParam(param);  

  82.         encoder.encode(bufferedImage);  

  83.         out.close();  

  84.     }  

  85. }  

3. 设置 http 代理

Java代码  收藏代码

  1. package org.demo.common;  

  2.   

  3. import java.io.BufferedReader;  

  4. import java.io.InputStream;  

  5. import java.io.InputStreamReader;  

  6. import java.net.URL;  

  7. import java.net.URLConnection;  

  8. import java.util.regex.Matcher;  

  9. import java.util.regex.Pattern;  

  10.   

  11. /** 

  12.  * 设置 http 代理 

  13.  * @author   

  14.  * @date    2010-6-19 

  15.  * @file    org.demo.common.HttpProxy.java 

  16.  */  

  17. public class HttpProxy {  

  18.     public static void main(String[] args)throws Exception {  

  19.         // 设置 http 代理  

  20.         setHttpProxy("206.224.254.10", "80", "", "");  

  21.         // 访问一个网页  

  22.         URL url = new URL("http://www.7daili.com/");  

  23.         URLConnection conn = url.openConnection();  

  24.         InputStream in = conn.getInputStream();  

  25.         InputStreamReader reader = new InputStreamReader(in,"utf-8");  

  26.         BufferedReader bf = new BufferedReader(reader);  

  27.         StringBuilder sb = new StringBuilder(1024);  

  28.         String line = null;  

  29.         while((line = bf.readLine()) != null){  

  30.             sb.append(line).append('\n');  

  31.         }  

  32.         bf.close();  

  33.         // 取出当前的客户端ip ip格式:[您的IP:12.34.56.78(地理位置)]  

  34.         String regex = "(您的IP\\:.*\\))\\s";  

  35.         Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);  

  36.         Matcher matcher = pattern.matcher(sb);  

  37.         if (matcher.find()){  

  38.             System.out.println("--> " + matcher.group(1));  

  39.         } else {  

  40.             System.out.println("--> " + "未找到ip");  

  41.         }     

  42.     }  

  43.     /** 

  44.      * 设置 http 代理 

  45.      * @param host 

  46.      * @param port 

  47.      * @param user 

  48.      * @param pass 

  49.      */  

  50.     public static void setHttpProxy(String host,String port,  

  51.                                     String user,String pass){  

  52.         System.getProperties().setProperty("http.proxyHost", host);  

  53.         System.getProperties().setProperty("http.proxyPort", port);  

  54.         System.getProperties().setProperty("http.proxyUser", user);  

  55.         System.getProperties().setProperty("http.proxyPassword", pass);  

  56.     }  

  57. }  

4. 解析 XML 文件

Java代码  收藏代码

  1. package org.demo.common;  

  2.   

  3. import java.io.ByteArrayInputStream;  

  4. import java.util.ArrayList;  

  5. import java.util.List;  

  6.   

  7. import javax.xml.parsers.DocumentBuilder;  

  8. import javax.xml.parsers.DocumentBuilderFactory;  

  9.   

  10. import org.w3c.dom.Document;  

  11. import org.w3c.dom.Element;  

  12. import org.w3c.dom.Node;  

  13. import org.w3c.dom.NodeList;  

  14.   

  15. /** 

  16.  * 解析 XML 文件 

  17.  * @author   

  18.  * @date    2010-6-21 

  19.  * @file    org.demo.common.XmlTools.java 

  20.  */  

  21. public class XmlTools {  

  22.   

  23.     /** 

  24.      * @param args 

  25.      */  

  26.     public static void main(String[] args)throws Exception {  

  27.         byte[] bytes = getXml().getBytes();  

  28.         ByteArrayInputStream in = new ByteArrayInputStream(bytes);  

  29.         // --  

  30.         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  

  31.         DocumentBuilder db = dbf.newDocumentBuilder();  

  32.         Document document = db.parse(in);  

  33.         Element root = document.getDocumentElement();  

  34.         // -- 获得所有的 student 元素  

  35.         List<Element> students = getChildren(root, "student");  

  36.         for(int i=0; i < students.size(); i++){  

  37.             Element student = students.get(i);  

  38.             String id = student.getAttribute("id");  

  39.             // -- 获得 student 元素的所有子元素  

  40.             NodeList nodeList = student.getChildNodes();  

  41.             System.out.print("[id:" + id );  

  42.             for(int j=0; j < nodeList.getLength(); j++){  

  43.                 Node node = nodeList.item(j);  

  44.                 if(node.getNodeType() == Node.ELEMENT_NODE){  

  45.                     System.out.print("," + node.getNodeName() + ":" + node.getTextContent());  

  46.                 }  

  47.             }  

  48.             System.out.println("]");          

  49.         }  

  50.         in.close();  

  51.     }  

  52.     /** 

  53.      * 获取子元素 

  54.      * @param parent 

  55.      * @param name 

  56.      * @return 

  57.      */  

  58.     public static List<Element> getChildren(Element parent,String name){  

  59.         List<Element> list = new ArrayList<Element>();  

  60.         Node node = parent.getFirstChild();  

  61.         while(node != null){  

  62.             if(node instanceof Element){  

  63.                 if(name.equals(((Element)node).getTagName())){  

  64.                     list.add((Element)node);  

  65.                 }  

  66.             }  

  67.             node = node.getNextSibling();  

  68.         }  

  69.         return list;  

  70.     }  

  71.     /** 

  72.      * 创建一个 XML 格式的 String 

  73.      * @return 

  74.      */  

  75.     public static String getXml(){  

  76.         // --  

  77.         StringBuilder sb = new StringBuilder();  

  78.         sb.append("<?xml version='1.0' encoding='utf-8'?>");  

  79.         sb.append("<root>");  

  80.         sb.append("  <student id='01'>");  

  81.         sb.append("    <name>Zhangs</name>");  

  82.         sb.append("    <grade>A</grade>");  

  83.         sb.append("    <age>20</age>");  

  84.         sb.append("  </student>");  

  85.         sb.append("  <student id='02'>");  

  86.         sb.append("    <name>Lis</name>");  

  87.         sb.append("    <grade>B</grade>");  

  88.         sb.append("    <age>18</age>");  

  89.         sb.append("  </student>");  

  90.         sb.append("</root>");  

  91.         return sb.toString();  

  92.     }  

  93. }  

5. 创建 zip 文件

Java代码  收藏代码

  1. package org.demo.common;  

  2.   

  3. import java.io.BufferedInputStream;  

  4. import java.io.File;  

  5. import java.io.FileInputStream;  

  6. import java.io.FileOutputStream;  

  7. import java.io.IOException;  

  8. import java.util.HashSet;  

  9. import java.util.Set;  

  10. import java.util.zip.CRC32;  

  11. import java.util.zip.ZipEntry;  

  12. import java.util.zip.ZipOutputStream;  

  13.   

  14. /** 

  15.  * 创建 zip 文档 

  16.  * @author   

  17.  * @date    2010-6-20 

  18.  * @file    org.demo.common.ZipTools.java 

  19.  */  

  20. public class ZipTools {  

  21.     public static void main(String[] args)throws Exception {  

  22.         // --  

  23.         String base = "D:/workspace/eclipse_wk/myProject/src/src-java/org/";  

  24.         String[] files = {"demo"};  

  25.         createZipFile(base, "tmp.zip", files);  

  26.     }  

  27.     /** 

  28.      * 创建一个压缩文件 

  29.      * @param base 

  30.      *        The root path end with '/' 

  31.      * @param zipName 

  32.      * @param files 

  33.      *        The files in base directory. 

  34.      * @return 该压缩文件的绝对路径 

  35.      */  

  36.     public static String createZipFile(String base,String zipName,String[] files){  

  37.         zipName = base + zipName;  

  38.         ZipOutputStream zipout = null;  

  39.         try{  

  40.             zipout = new ZipOutputStream(new FileOutputStream(zipName));  

  41.             // 去除重复的 file   

  42.             Set<String> set = new HashSet<String>();  

  43.             for(String fname : files){  

  44.                 set.add(fname);  

  45.             }  

  46.             for(String fname : set){                  

  47.                 zip(zipout,new File(base + fname),"");  

  48.             }  

  49.         } catch(Exception e){  

  50.             e.printStackTrace();  

  51.         } finally{  

  52.             try{  

  53.                 if(zipout != null){  

  54.                     zipout.flush();  

  55.                     zipout.close();  

  56.                 }                 

  57.             }catch(Exception e){  

  58.                 e.printStackTrace();  

  59.             }  

  60.         }  

  61.         return zipName;  

  62.     }  

  63.     /** 

  64.      * 将文件 file 写入到 zip 输出流中 

  65.      * @param out 

  66.      * @param file 

  67.      * @param base 

  68.      */  

  69.     private static void zip(ZipOutputStream out,File file,String base) throws IOException{  

  70.         if (base == null){  

  71.             base = "";  

  72.         }  

  73.         base += file.getName();  

  74.         if(file.isDirectory()){  

  75.             base += '/';  

  76.             ZipEntry entry = new ZipEntry(base);     // 创建一个目录条目 [以 / 结尾]  

  77.             out.putNextEntry(entry);                 // 向输出流中写入下一个目录条目  

  78.             File[] fileArr = file.listFiles();       // 递归写入目录下的所有文件  

  79.             for(File f : fileArr){  

  80.                 zip(out,f,base);  

  81.             }  

  82.         } else if (file.isFile()){            

  83.             ZipEntry entry = new ZipEntry(base);     // 创建一个文件条目  

  84.             entry.setCrc(getCRC32(file));  

  85.             entry.setMethod(ZipEntry.STORED);  

  86.             entry.setCompressedSize(file.length());  

  87.             // --  

  88.             out.putNextEntry(entry);                 // 向输出流中写入下一个文件条目  

  89.             FileInputStream in = new FileInputStream(file); // 写入文件内容  

  90.             byte[] buf = new byte[1024];  

  91.             int count;  

  92.             while((count = in.read(buf)) != -1){  

  93.                 out.write(buf,0,count);  

  94.             }  

  95.             in.close();  

  96.         }  

  97.     }  

  98.     /** 

  99.      * 计算 file 的 CRC-32 校验和 

  100.      * @param file 

  101.      * @return 

  102.      */  

  103.     public static long getCRC32(File file)throws IOException{  

  104.         // --  

  105.         CRC32 crc = new CRC32();  

  106.         // --  

  107.         BufferedInputStream bins = new BufferedInputStream(new FileInputStream(file));            

  108.         byte[] buf = new byte[1024];  

  109.         int count;  

  110.         // --  

  111.         while((count = bins.read(buf)) != -1){  

  112.             crc.update(buf, 0, count);  

  113.         }  

  114.         bins.close();  

  115.         return crc.getValue();  

  116.     }  

  117. }  

6. 调整数组大小

Java代码  收藏代码

  1. package org.demo.common;  

  2.   

  3. import java.lang.reflect.Array;  

  4.   

  5. /** 

  6.  * 调整数组大小 

  7.  * @author   

  8.  * @date    2010-6-21 

  9.  * @file    org.demo.common.ArrayTools.java 

  10.  */  

  11. public class ArrayTools {  

  12.   

  13.     /** 

  14.      * @param args 

  15.      */  

  16.     public static void main(String[] args) {  

  17.         int[] arr = new int[10];  

  18.         arr[0] = 1;  

  19.         arr[1] = 2;  

  20.         arr[2] = 3;  

  21.         arr[3] = 4;  

  22.         arr[4] = 5;  

  23.         arr[5] = 6;  

  24.         arr[6] = 7;  

  25.         // 调整数组大小  

  26.         int[] tmp = (int[])arrayResize(arr, 7);  

  27.         // 输出新数组信息  

  28.         System.out.println("length=" + tmp.length);  

  29.         System.out.print("[");  

  30.         for(int i=0; i < tmp.length; i++){  

  31.             System.out.print(tmp[i]);  

  32.             if(i < tmp.length -1){  

  33.                 System.out.print(",");  

  34.             }  

  35.         }  

  36.         System.out.println("]");  

  37.     }  

  38.     /** 

  39.      * 调整数组的大小 

  40.      * @param oldArray 

  41.      * @param newSize 

  42.      */  

  43.     public static Object arrayResize(Object oldArray,int newSize){  

  44.         // -- 数组大小  

  45.         int oldSize = Array.getLength(oldArray);  

  46.         newSize = Math.min(oldSize, newSize);  

  47.         // -- 数组内 元素的类型  

  48.         Class<?> type = oldArray.getClass().getComponentType();         

  49.         // -- 新建数组  

  50.         Object newArray = Array.newInstance(type, newSize);  

  51.         System.arraycopy(oldArray, 0, newArray, 0, newSize);  

  52.         return newArray;  

  53.     }  

  54. }  

7. 数组 -> Map

Java代码  收藏代码

  1. package org.demo.common;  

  2.   

  3. import java.util.Map;  

  4. import org.apache.commons.lang.ArrayUtils;  

  5. // --  

  6. // library dependencies  

  7. //  * commons-lang-2.5.jar  

  8. // --  

  9. /** 

  10.  * Array to Map 

  11.  * @author   

  12.  * @date    2010-6-20 

  13.  * @file    org.demo.common.Array2Map.java 

  14.  */  

  15. public class Array2Map {  

  16.     @SuppressWarnings("unchecked")  

  17.     public static void main(String[] args) {  

  18.         String[][] arr = new String[][]{{"a","aa"},{"b","bb"}};  

  19.         Map map = ArrayUtils.toMap(arr);  

  20.         System.out.println("map=" + map);  

  21.     }  

  22. }  

 

8. 使用 XSLT 转换 XML

Java代码  收藏代码

  1. package local;  

  2.   

  3. import java.io.ByteArrayOutputStream;  

  4. import java.io.File;  

  5. import java.io.FileInputStream;  

  6. import java.io.IOException;  

  7. import java.io.InputStream;  

  8.   

  9. import javax.xml.transform.Result;  

  10. import javax.xml.transform.Source;  

  11. import javax.xml.transform.Transformer;  

  12. import javax.xml.transform.TransformerException;  

  13. import javax.xml.transform.TransformerFactory;  

  14. import javax.xml.transform.sax.SAXSource;  

  15. import javax.xml.transform.stream.StreamResult;  

  16. import javax.xml.transform.stream.StreamSource;  

  17.   

  18. import org.xml.sax.InputSource;  

  19.   

  20. /** 

  21.  * 使用 XSLT 转换 XML 

  22.  * @author   

  23.  * @date    2010-7-8 

  24.  * @file    local.XsltTools.java 

  25.  */  

  26. public class XsltTools {  

  27.       

  28.     /** 

  29.      * 测试 

  30.      * @param args 

  31.      * @throws IOException  

  32.      * @throws TransformerException  

  33.      */  

  34.     public static void main(String[] args) throws Exception {         

  35.         String xsl = "D:/local/transform.xsl";  

  36.         String xml = "D:/local/customer.xml";  

  37.         InputStream in = new FileInputStream(xsl);  

  38.         // 构建输入输出流  

  39.         ByteArrayOutputStream out = new ByteArrayOutputStream();  

  40.         Source from = new StreamSource(new File(xml));  

  41.         Result to = new StreamResult(out);  

  42.         // 构建转换器并执行转换  

  43.         Transformer transformer = getTransformer(in);  

  44.         transformer.transform(from, to);  

  45.         // 输出转换后结果  

  46.         String result = out.toString();  

  47.         System.out.println(result);  

  48.     }  

  49.     /** 

  50.      * 创建并返回 transformer 

  51.      * @param in_xsl 

  52.      * @return a Transformer instance or null. 

  53.      */  

  54.     public static Transformer getTransformer(InputStream in_xsl){  

  55.         Transformer transformer = null;  

  56.         try {  

  57.             SAXSource xsl = new SAXSource(new InputSource(in_xsl));  

  58.             transformer = TransformerFactory.newInstance()  

  59.                                             .newTransformer(xsl);                     

  60.         } catch (Exception e) {  

  61.             e.printStackTrace();  

  62.         }  

  63.         return transformer;  

  64.     }     

  65. }   

// customer.xml

Xml代码  收藏代码

  1. <?xml version="1.0" encoding="utf-8"?>  

  2. <mysql>  

  3.     <customer>  

  4.         <key>001</key>  

  5.         <firstName>Zhang</firstName>  

  6.         <lastName>san</lastName>  

  7.         <comment>This is a comment</comment>  

  8.     </customer>  

  9. </mysql>  

 // transform.xsl

Xml代码  收藏代码

  1. <?xml version="1.0" encoding="utf-8"?>  

  2. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">  

  3. <xsl:template match="/mysql">  

  4. <db2>  

  5.   <xsl:for-each select="customer">      

  6.     <client id="{key}">             

  7.         <name><xsl:value-of select="concat(firstName,lastName)"/></name>          

  8.         <note><xsl:value-of select="comment"/></note>  

  9.     </client>  

  10.   </xsl:for-each>      

  11. </db2>  

  12. </xsl:template>  

  13. </xsl:stylesheet>  

// 输出结果

 

9. 类型转换

Java代码  收藏代码

  1. /** 

  2.  * 类型转换: String -> type 

  3.  * @param <T> 

  4.  * @param value 

  5.  * @param type 

  6.  * @return 

  7.  */  

  8. @SuppressWarnings("unchecked")  

  9. public <T>T typeConvert(String value,Class<T> type){  

  10.     PropertyEditor pe = PropertyEditorManager.findEditor(type);  

  11.     pe.setAsText(value);  

  12.     return (T)pe.getValue();  

  13. }  

  

10. java 计算日期差

Java代码  收藏代码

  1. /** 

  2.  * 计算日期差 

  3.  * @param start 

  4.  * @param end 

  5.  * @return 

  6.  */  

  7. public static long subtract(Date start,Date end){  

  8.     // 先个自计算出距离 1970-1-1 的日期差,然后相减  

  9.     long one_day = 24*60*60*1000;  

  10.     long stime = start.getTime();  

  11.     long etime = end.getTime();  

  12.     long sdays = stime/one_day;  

  13.     long edays = etime/one_day;  

  14.     // 若 start < 1970-1-1,则日期差了一天,需要修正  

  15.     if (stime < 0){  

  16.         sdays--;  

  17.     }  

  18.     // 若 end < 1970-1-1,则日期差了一天,需要修正  

  19.     if (etime < 0){  

  20.         edays--;  

  21.     }  

  22.     return edays - sdays;  

  23. }  

  

转载于:https://my.oschina.net/u/2365087/blog/413698

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值