1. 屏幕截圖java
public static void main(String[] args)throws Exception { mysql
String filename = "d:\\Temp\\screen.png"; sql
// 獲取屏幕尺寸 apache
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize(); 數組
Rectangle rectangle = new Rectangle(dimension); app
// 建立圖像 dom
BufferedImage image = new Robot().createScreenCapture(rectangle); eclipse
// 保存到磁盤 測試
// @see ImageIO#getWriterFormatNames();
ImageIO.write(image, "png", new File(filename));
}
2. 縮放圖像
package org.demo.common;
import java.awt.Container;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* 建立縮略圖
* @author
* @date 2010-6-19
* @file org.demo.common.ImageThumbnail.java
*/
public class ImageThumbnail {
/**
* @param args
*/
public static void main(String[] args)throws Exception {
String inFilename = "d:\\Temp\\demo1.png";
String outFilename = "d:\\Temp\\demo2.png";
createThumbnail(inFilename, outFilename, 800, 600, 0.75f);
}
/**
* 建立縮略圖
* @param inFilename
* @param outFilename
* @param thumbWidth
* @param thumbHeight
* @param quality
* [0.0,1.0]
* @return
*/
public static void createThumbnail(
String inFilename,String outFilename,
int thumbWidth,int thumbHeight,float quality)
throws IOException,InterruptedException{
// 加載圖像
Image image = Toolkit.getDefaultToolkit().getImage(inFilename);
// 建立圖像追蹤器
MediaTracker mediaTracker = new MediaTracker(new Container());
mediaTracker.addImage(image, 0);
/** !必須等圖像徹底加載到內存以後才能執行後續操做! */
mediaTracker.waitForID(0);
System.out.println("isErrorAny=" + mediaTracker.isErrorAny());
// 計算等比例縮放的實際 寬高值
double thumbRatio = thumbWidth/thumbHeight;
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
double imageRatio = (double)imageWidth/imageHeight;
if (thumbRatio < imageRatio){
// --> height
thumbHeight = (int)(thumbWidth/imageRatio);
} else {
// --> width
thumbWidth = (int)(thumbHeight * imageRatio);
}
// 建立內存縮略圖
BufferedImage bufferedImage = new BufferedImage(thumbWidth,
thumbHeight,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bufferedImage.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
// 將內存縮略圖 寫入 文件
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);
param.setQuality(quality,false);
encoder.setJPEGEncodeParam(param);
encoder.encode(bufferedImage);
out.close();
}
}
3. 設置 http 代理
package org.demo.common;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 設置 http 代理
* @author
* @date 2010-6-19
* @file org.demo.common.HttpProxy.java
*/
public class HttpProxy {
public static void main(String[] args)throws Exception {
// 設置 http 代理
setHttpProxy("206.224.254.10", "80", "", "");
// 訪問一個網頁
URL url = new URL("http://www.7daili.com/");
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
InputStreamReader reader = new InputStreamReader(in,"utf-8");
BufferedReader bf = new BufferedReader(reader);
StringBuilder sb = new StringBuilder(1024);
String line = null;
while((line = bf.readLine()) != null){
sb.append(line).append('\n');
}
bf.close();
// 取出當前的客戶端ip ip格式:[您的IP:12.34.56.78(地理位置)]
String regex = "(您的IP\\:.*\\))\\s";
Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(sb);
if (matcher.find()){
System.out.println("--> " + matcher.group(1));
} else {
System.out.println("--> " + "未找到ip");
}
}
/**
* 設置 http 代理
* @param host
* @param port
* @param user
* @param pass
*/
public static void setHttpProxy(String host,String port,
String user,String pass){
System.getProperties().setProperty("http.proxyHost", host);
System.getProperties().setProperty("http.proxyPort", port);
System.getProperties().setProperty("http.proxyUser", user);
System.getProperties().setProperty("http.proxyPassword", pass);
}
}
4. 解析 XML 文件
package org.demo.common;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;
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;
/**
* 解析 XML 文件
* @author
* @date 2010-6-21
* @file org.demo.common.XmlTools.java
*/
public class XmlTools {
/**
* @param args
*/
public static void main(String[] args)throws Exception {
byte[] bytes = getXml().getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
// --
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(in);
Element root = document.getDocumentElement();
// -- 得到全部的 student 元素
List<Element> students = getChildren(root, "student");
for(int i=0; i < students.size(); i++){
Element student = students.get(i);
String id = student.getAttribute("id");
// -- 得到 student 元素的全部子元素
NodeList nodeList = student.getChildNodes();
System.out.print("[id:" + id );
for(int j=0; j < nodeList.getLength(); j++){
Node node = nodeList.item(j);
if(node.getNodeType() == Node.ELEMENT_NODE){
System.out.print("," + node.getNodeName() + ":" + node.getTextContent());
}
}
System.out.println("]");
}
in.close();
}
/**
* 獲取子元素
* @param parent
* @param name
* @return
*/
public static List<Element> getChildren(Element parent,String name){
List<Element> list = new ArrayList<Element>();
Node node = parent.getFirstChild();
while(node != null){
if(node instanceof Element){
if(name.equals(((Element)node).getTagName())){
list.add((Element)node);
}
}
node = node.getNextSibling();
}
return list;
}
/**
* 建立一個 XML 格式的 String
* @return
*/
public static String getXml(){
// --
StringBuilder sb = new StringBuilder();
sb.append("<?xml version='1.0' encoding='utf-8'?>");
sb.append("<root>");
sb.append(" <student id='01'>");
sb.append(" <name>Zhangs</name>");
sb.append(" <grade>A</grade>");
sb.append(" <age>20</age>");
sb.append(" </student>");
sb.append(" <student id='02'>");
sb.append(" <name>Lis</name>");
sb.append(" <grade>B</grade>");
sb.append(" <age>18</age>");
sb.append(" </student>");
sb.append("</root>");
return sb.toString();
}
}
5. 建立 zip 文件
package org.demo.common;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 建立 zip 文檔
* @author
* @date 2010-6-20
* @file org.demo.common.ZipTools.java
*/
public class ZipTools {
public static void main(String[] args)throws Exception {
// --
String base = "D:/workspace/eclipse_wk/myProject/src/src-java/org/";
String[] files = {"demo"};
createZipFile(base, "tmp.zip", files);
}
/**
* 建立一個壓縮文件
* @param base
* The root path end with '/'
* @param zipName
* @param files
* The files in base directory.
* @return 該壓縮文件的絕對路徑
*/
public static String createZipFile(String base,String zipName,String[] files){
zipName = base + zipName;
ZipOutputStream zipout = null;
try{
zipout = new ZipOutputStream(new FileOutputStream(zipName));
// 去除重複的 file
Set<String> set = new HashSet<String>();
for(String fname : files){
set.add(fname);
}
for(String fname : set){
zip(zipout,new File(base + fname),"");
}
} catch(Exception e){
e.printStackTrace();
} finally{
try{
if(zipout != null){
zipout.flush();
zipout.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
return zipName;
}
/**
* 將文件 file 寫入到 zip 輸出流中
* @param out
* @param file
* @param base
*/
private static void zip(ZipOutputStream out,File file,String base) throws IOException{
if (base == null){
base = "";
}
base += file.getName();
if(file.isDirectory()){
base += '/';
ZipEntry entry = new ZipEntry(base); // 建立一個目錄條目 [以 / 結尾]
out.putNextEntry(entry); // 向輸出流中寫入下一個目錄條目
File[] fileArr = file.listFiles(); // 遞歸寫入目錄下的全部文件
for(File f : fileArr){
zip(out,f,base);
}
} else if (file.isFile()){
ZipEntry entry = new ZipEntry(base); // 建立一個文件條目
entry.setCrc(getCRC32(file));
entry.setMethod(ZipEntry.STORED);
entry.setCompressedSize(file.length());
// --
out.putNextEntry(entry); // 向輸出流中寫入下一個文件條目
FileInputStream in = new FileInputStream(file); // 寫入文件內容
byte[] buf = new byte[1024];
int count;
while((count = in.read(buf)) != -1){
out.write(buf,0,count);
}
in.close();
}
}
/**
* 計算 file 的 CRC-32 校驗和
* @param file
* @return
*/
public static long getCRC32(File file)throws IOException{
// --
CRC32 crc = new CRC32();
// --
BufferedInputStream bins = new BufferedInputStream(new FileInputStream(file));
byte[] buf = new byte[1024];
int count;
// --
while((count = bins.read(buf)) != -1){
crc.update(buf, 0, count);
}
bins.close();
return crc.getValue();
}
}
6. 調整數組大小
package org.demo.common;
import java.lang.reflect.Array;
/**
* 調整數組大小
* @author
* @date 2010-6-21
* @file org.demo.common.ArrayTools.java
*/
public class ArrayTools {
/**
* @param args
*/
public static void main(String[] args) {
int[] arr = new int[10];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
arr[5] = 6;
arr[6] = 7;
// 調整數組大小
int[] tmp = (int[])arrayResize(arr, 7);
// 輸出新數組信息
System.out.println("length=" + tmp.length);
System.out.print("[");
for(int i=0; i < tmp.length; i++){
System.out.print(tmp[i]);
if(i < tmp.length -1){
System.out.print(",");
}
}
System.out.println("]");
}
/**
* 調整數組的大小
* @param oldArray
* @param newSize
*/
public static Object arrayResize(Object oldArray,int newSize){
// -- 數組大小
int oldSize = Array.getLength(oldArray);
newSize = Math.min(oldSize, newSize);
// -- 數組內 元素的類型
Class<?> type = oldArray.getClass().getComponentType();
// -- 新建數組
Object newArray = Array.newInstance(type, newSize);
System.arraycopy(oldArray, 0, newArray, 0, newSize);
return newArray;
}
}
7. 數組 -> Map
package org.demo.common;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
// --
// library dependencies
// * commons-lang-2.5.jar
// --
/**
* Array to Map
* @author
* @date 2010-6-20
* @file org.demo.common.Array2Map.java
*/
public class Array2Map {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
String[][] arr = new String[][]{{"a","aa"},{"b","bb"}};
Map map = ArrayUtils.toMap(arr);
System.out.println("map=" + map);
}
}
8. 使用 XSLT 轉換 XML
package local;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.xml.sax.InputSource;
/**
* 使用 XSLT 轉換 XML
* @author
* @date 2010-7-8
* @file local.XsltTools.java
*/
public class XsltTools {
/**
* 測試
* @param args
* @throws IOException
* @throws TransformerException
*/
public static void main(String[] args) throws Exception {
String xsl = "D:/local/transform.xsl";
String xml = "D:/local/customer.xml";
InputStream in = new FileInputStream(xsl);
// 構建輸入輸出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
Source from = new StreamSource(new File(xml));
Result to = new StreamResult(out);
// 構建轉換器並執行轉換
Transformer transformer = getTransformer(in);
transformer.transform(from, to);
// 輸出轉換後結果
String result = out.toString();
System.out.println(result);
}
/**
* 建立並返回 transformer
* @param in_xsl
* @return a Transformer instance or null.
*/
public static Transformer getTransformer(InputStream in_xsl){
Transformer transformer = null;
try {
SAXSource xsl = new SAXSource(new InputSource(in_xsl));
transformer = TransformerFactory.newInstance()
.newTransformer(xsl);
} catch (Exception e) {
e.printStackTrace();
}
return transformer;
}
}
// customer.xml
<?xml version="1.0" encoding="utf-8"?>
<mysql>
<customer>
<key>001</key>
<firstName>Zhang</firstName>
<lastName>san</lastName>
<comment>This is a comment</comment>
</customer>
</mysql>
// transform.xsl
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/mysql">
<db2>
<xsl:for-each select="customer">
<client id="{key}">
<name><xsl:value-of select="concat(firstName,lastName)"/></name>
<note><xsl:value-of select="comment"/></note>
</client>
</xsl:for-each>
</db2>
</xsl:template>
</xsl:stylesheet>
// 輸出結果
9. 類型轉換
/**
* 類型轉換: String -> type
* @param <T>
* @param value
* @param type
* @return
*/
@SuppressWarnings("unchecked")
public <T>T typeConvert(String value,Class<T> type){
PropertyEditor pe = PropertyEditorManager.findEditor(type);
pe.setAsText(value);
return (T)pe.getValue();
}
10. java 計算日期差
/**
* 計算日期差
* @param start
* @param end
* @return
*/
public static long subtract(Date start,Date end){
// 先個自計算出距離 1970-1-1 的日期差,而後相減
long one_day = 24*60*60*1000;
long stime = start.getTime();
long etime = end.getTime();
long sdays = stime/one_day;
long edays = etime/one_day;
// 若 start < 1970-1-1,則日期差了一天,須要修正
if (stime < 0){
sdays--;
}
// 若 end < 1970-1-1,則日期差了一天,須要修正
if (etime < 0){
edays--;
}
return edays - sdays;
}