java學習

          java學習

           

          多個有用的程序

          1. 字符串有整型的相互轉換

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


          2. 向文件末尾添加內容

          01   
          02 BufferedWriter out = null;  
          03 try {  
          04     out = new BufferedWriter(new FileWriter(”filename”, true));  
          05     out.write(”aString”);  
          06 } catch (IOException e) {  
          07     // error processing code  
          08 } finally {  
          09     if (out != null) {  
          10         out.close();  
          11     }  
          12

          3. 得到當前方法的名字

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

          4. 轉字符串到日期

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

          或者是:

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

          5. 使用JDBC鏈接Oracle

          01 public class OracleJdbcTest  
          02 {  
          03     String driverClass = "oracle.jdbc.driver.OracleDriver";  
          04   
          05     Connection con;  
          06   
          07     public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException  
          08     {  
          09         Properties props = new Properties();  
          10         props.load(fs);  
          11         String url = props.getProperty("db.url");  
          12         String userName = props.getProperty("db.user");  
          13         String password = props.getProperty("db.password");  
          14         Class.forName(driverClass);  
          15   
          16         con=DriverManager.getConnection(url, userName, password);  
          17     }  
          18   
          19     public void fetch() throws SQLException, IOException  
          20     {  
          21         PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");  
          22         ResultSet rs = ps.executeQuery();  
          23   
          24         while (rs.next())  
          25         {  
          26             // do the thing you do  
          27         }  
          28         rs.close();  
          29         ps.close();  
          30     }  
          31   
          32     public static void main(String[] args)  
          33     {  
          34         OracleJdbcTest test = new OracleJdbcTest();  
          35         test.init();  
          36         test.fetch();  
          37     }  
          38

          6. 把 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進行快速的文件拷貝

          01 public static void fileCopy( File in, File out )  
          02             throws IOException  
          03     {  
          04         FileChannel inChannel = new FileInputStream( in ).getChannel();  
          05         FileChannel outChannel = new FileOutputStream( out ).getChannel();  
          06         try 
          07         {  
          08 //          inChannel.transferTo(0, inChannel.size(), outChannel);      // original -- apparently has trouble copying large files on Windows  
          09   
          10             // magic number for Windows, 64Mb - 32Kb)  
          11             int maxCount = (64 * 1024 * 1024) - (32 * 1024);  
          12             long size = inChannel.size();  
          13             long position = 0;  
          14             while ( position < size )  
          15             {  
          16                position += inChannel.transferTo( position, maxCount, outChannel );  
          17             }  
          18         }  
          19         finally 
          20         {  
          21             if ( inChannel != null )  
          22             {  
          23                inChannel.close();  
          24             }  
          25             if ( outChannel != null )  
          26             {  
          27                 outChannel.close();  
          28             }  
          29         }  
          30     

          8. 創建圖片的縮略圖

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

          9. 創建 JSON 格式的數據

          請先閱讀這篇文章 了解一些細節,
          并下面這個JAR 文件:json-rpc-1.0.jar (75 kb)

          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

          閱讀這篇文章 了解更多細節

          01   
          02 import java.io.File;  
          03 import java.io.FileOutputStream;  
          04 import java.io.OutputStream;  
          05 import java.util.Date;  
          06   
          07 import com.lowagie.text.Document;  
          08 import com.lowagie.text.Paragraph;  
          09 import com.lowagie.text.pdf.PdfWriter;  
          10   
          11 public class GeneratePDF {  
          12   
          13     public static void main(String[] args) {  
          14         try {  
          15             OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));  
          16   
          17             Document document = new Document();  
          18             PdfWriter.getInstance(document, file);  
          19             document.open();  
          20             document.add(new Paragraph("Hello Kiran"));  
          21             document.add(new Paragraph(new Date().toString()));  
          22   
          23             document.close();  
          24             file.close();  
          25   
          26         } catch (Exception e) {  
          27   
          28             e.printStackTrace();  
          29         }  
          30     }  
          31

          11. HTTP 代理設置

          閱讀這篇 文章 了解更多細節。

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

          12. 單實例Singleton 示例

          請先閱讀這篇文章 了解更多信息

          01   
          02 public class SimpleSingleton {  
          03     private static SimpleSingleton singleInstance =  new SimpleSingleton();  
          04   
          05     //Marking default constructor private  
          06     //to avoid direct instantiation.  
          07     private SimpleSingleton() {  
          08     }  
          09   
          10     //Get instance for class SimpleSingleton  
          11     public static SimpleSingleton getInstance() {  
          12   
          13         return singleInstance;  
          14     }  
          15

          另一種實現

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

          13. 抓屏程序

          閱讀這篇文章 獲得更多信息。

          01 import java.awt.Dimension;  
          02 import java.awt.Rectangle;  
          03 import java.awt.Robot;  
          04 import java.awt.Toolkit;  
          05 import java.awt.image.BufferedImage;  
          06 import javax.imageio.ImageIO;  
          07 import java.io.File;  
          08   
          09 ...  
          10   
          11 public void captureScreen(String fileName) throws Exception {  
          12   
          13    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();  
          14    Rectangle screenRectangle = new Rectangle(screenSize);  
          15    Robot robot = new Robot();  
          16    BufferedImage image = robot.createScreenCapture(screenRectangle);  
          17    ImageIO.write(image, "png", new File(fileName));  
          18   
          19 }  
          20 ... 

           

           

          14. 列出文件和目錄

          01 File dir = new File("directoryName");  
          02   String[] children = dir.list();  
          03   if (children == null) {  
          04       // Either dir does not exist or is not a directory  
          05   } else {  
          06       for (int i=0; i < children.length; i++) {  
          07           // Get filename of file or directory  
          08           String filename = children[i];  
          09       }  
          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. 創建ZIP和JAR文件

          01   
          02 import java.util.zip.*;  
          03 import java.io.*;  
          04   
          05 public class ZipIt {  
          06     public static void main(String args[]) throws IOException {  
          07         if (args.length < 2) {  
          08             System.err.println("usage: java ZipIt Zip.zip file1 file2 file3");  
          09             System.exit(-1);  
          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         FileOutputStream fos = new FileOutputStream(zipFile);  
          17         ZipOutputStream zos = new ZipOutputStream(fos);  
          18         int bytesRead;  
          19         byte[] buffer = new byte[1024];  
          20         CRC32 crc = new CRC32();  
          21         for (int i=1, n=args.length; i < n; i++) {  
          22             String name = args[i];  
          23             File file = new File(name);  
          24             if (!file.exists()) {  
          25                 System.err.println("Skipping: " + name);  
          26                 continue;  
          27             }  
          28             BufferedInputStream bis = new BufferedInputStream(  
          29                 new FileInputStream(file));  
          30             crc.reset();  
          31             while ((bytesRead = bis.read(buffer)) != -1) {  
          32                 crc.update(buffer, 0, bytesRead);  
          33             }  
          34             bis.close();  
          35             // Reset to beginning of input stream  
          36             bis = new BufferedInputStream(  
          37                 new FileInputStream(file));  
          38             ZipEntry entry = new ZipEntry(name);  
          39             entry.setMethod(ZipEntry.STORED);  
          40             entry.setCompressedSize(file.length());  
          41             entry.setSize(file.length());  
          42             entry.setCrc(crc.getValue());  
          43             zos.putNextEntry(entry);  
          44             while ((bytesRead = bis.read(buffer)) != -1) {  
          45                 zos.write(buffer, 0, bytesRead);  
          46             }  
          47             bis.close();  
          48         }  
          49         zos.close();  
          50     }  
          51

          16. 解析/讀取XML 文件

          XML文件

          01 <?xml version="1.0"?> 
          02 <students
          03     <student
          04         <name>John</name
          05         <grade>B</grade
          06         <age>12</age
          07     </student
          08     <student
          09         <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代碼

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

          17. 把 Array 轉換成 Map 

          01   
          02 import java.util.Map;  
          03 import org.apache.commons.lang.ArrayUtils;  
          04   
          05 public class Main {  
          06   
          07   public static void main(String[] args) {  
          08     String[][] countries = { { "United States", "New York" }, { "United Kingdom", "London" },  
          09         { "Netherland", "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" } };  
          10   
          11     Map countryCapitals = ArrayUtils.toMap(countries);  
          12   
          13     System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));  
          14     System.out.println("Capital of France is " + countryCapitals.get("France"));  
          15   }  
          16

          18. 發送郵件

          01 import javax.mail.*;  
          02 import javax.mail.internet.*;  
          03 import java.util.*;  
          04   
          05 public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException  
          06 {  
          07     boolean debug = false;  
          08   
          09      //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 請求

          01   
          02 import java.io.BufferedReader;  
          03 import java.io.InputStreamReader;  
          04 import java.net.URL;  
          05   
          06 public class Main {  
          07     public static void main(String[] args)  {  
          08         try {  
          09             URL my_url = new URL(");  
          10             BufferedReader br = new BufferedReader(new InputStreamReader(my_url.openStream()));  
          11             String strTemp = "";  
          12             while(null != (strTemp = br.readLine())){  
          13             System.out.println(strTemp);  
          14         }  
          15         } catch (Exception ex) {  
          16             ex.printStackTrace();  
          17         }  
          18     }  
          19 }

          20. 改變數組的大小

          01   
          02 /** 
          03 * Reallocates an array with a new size, and copies the contents 
          04 * of the old array to the new array. 
          05 * @param oldArray  the old array, to be reallocated. 
          06 * @param newSize   the new array size. 
          07 * @return          A new array with the same contents. 
          08 */ 
          09 private static Object resizeArray (Object oldArray, int newSize) {  
          10    int oldSize = java.lang.reflect.Array.getLength(oldArray);  
          11    Class elementType = oldArray.getClass().getComponentType();  
          12    Object newArray = java.lang.reflect.Array.newInstance(  
          13          elementType,newSize);  
          14    int preserveLength = Math.min(oldSize,newSize);  
          15    if (preserveLength > 0)  
          16       System.arraycopy (oldArray,0,newArray,0,preserveLength);  
          17    return newArray;  
          18 }  
          19   
          20 // Test routine for resizeArray().  
          21 public static void main (String[] args) {  
          22    int[] a = {1,2,3};  
          23    a = (int[])resizeArray(a,5);  
          24    a[3] = 4;  
          25    a[4] = 5;  
          26    for (int i=0; i<a.length; i++)  
          27       System.out.println (a[i]);  
          28 }

          posted on 2013-01-18 15:08 楊軍威 閱讀(161) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           

          導航

          統計

          常用鏈接

          留言簿

          隨筆檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 陇川县| 丽江市| 米脂县| 广丰县| 肇源县| 黄浦区| 穆棱市| 康定县| 分宜县| 揭东县| 罗源县| 桃江县| 峨眉山市| 阳曲县| 饶河县| 磐安县| 凤城市| 修武县| 古浪县| 天峨县| 仙居县| 上虞市| 楚雄市| 栾川县| 古丈县| 富阳市| 周至县| 宜春市| 阳原县| 甘孜| 天津市| 玛曲县| 清镇市| 阜宁县| 兴仁县| 泗阳县| 岱山县| 卢氏县| 西林县| 屯留县| 漠河县|