免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1631 | 回复: 1
打印 上一主题 下一主题

20个常用的java开发块 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-03-15 20:57 |只看该作者 |倒序浏览

20个常用的java开发块
  1. //1. 字符串有整型的相互转换   

  2. 002 String a = String.valueOf(2); //integer to numeric string   

  3. 003 int i = Integer.parseInt(a); //numeric string to an int  

  4. 004   

  5. 005 //2. 向文件末尾添加内容   

  6. 006 BufferedWriter out = null;   

  7. 007 try {   

  8. 008 out = new BufferedWriter(new FileWriter(”filename”, true));   

  9. 009 out.write(”aString”);   

  10. 010 } catch (IOException e) {   

  11. 011  // error processing code  

  12. 012   

  13. 013 } finally {   

  14. 014 if (out != null) {   

  15. 015 out.close();   

  16. 016 }  

  17. 017   

  18. 018 }  

  19. 019   

  20. 020 //3. 得到当前方法的名字   

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

  22. 022   

  23. 023 //4. 转字符串到日期   

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

  25. 025 //或者是:   

  26. 026 SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );   

  27. 027 Date date = format.parse( myString );  

  28. 028   

  29. 029 //5. 使用JDBC链接Oracle   

  30. 030 public class OracleJdbcTest   

  31. 031 {   

  32. 032  String driverClass = "oracle.jdbc.driver.OracleDriver";  

  33. 033   

  34. 034  Connection con;  

  35. 035   

  36. 036  public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException  

  37. 037  {   

  38. 038  Properties props = new Properties();   

  39. 039  props.load(fs);   

  40. 040  String url = props.getProperty("db.url");   

  41. 041  String userName = props.getProperty("db.user");   

  42. 042  String password = props.getProperty("db.password");   

  43. 043  Class.forName(driverClass);  

  44. 044   

  45. 045  con=DriverManager.getConnection(url, userName, password);   

  46. 046  }  

  47. 047   

  48. 048  public void fetch() throws SQLException, IOException   

  49. 049  {   

  50. 050  PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");   

  51. 051  ResultSet rs = ps.executeQuery();  

  52. 052   

  53. 053  while (rs.next())   

  54. 054  {   

  55. 055  // do the thing you do   

  56. 056  }   

  57. 057  rs.close();   

  58. 058  ps.close();   

  59. 059  }  

  60. 060   

  61. 061  public static void main(String[] args)   

  62. 062  {   

  63. 063  OracleJdbcTest test = new OracleJdbcTest();   

  64. 064  test.init();   

  65. 065  test.fetch();   

  66. 066  }   

  67. 067 }  

  68. 068   

  69. 069 6. 把 Java util.Date 转成 sql.Date   

  70. 070 java.util.Date utilDate = new java.util.Date();   

  71. 071 java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());  

  72. 072   

  73. 073 //7. 使用NIO进行快速的文件拷贝   

  74. 074  public static void fileCopy( File in, File out )   

  75. 075  throws IOException   

  76. 076  {   

  77. 077  FileChannel inChannel = new FileInputStream( in ).getChannel();   

  78. 078  FileChannel outChannel = new FileOutputStream( out ).getChannel();   

  79. 079  try  

  80. 080  {   

  81. 081 // inChannel.transferTo(0, inChannel.size(), outChannel); // original -- apparently has trouble copying large files on Windows

  82. 082   

  83. 083  // magic number for Windows, 64Mb - 32Kb)   

  84. 084  int maxCount = (64 * 1024 * 1024) - (32 * 1024);   

  85. 085  long size = inChannel.size();   

  86. 086  long position = 0;   

  87. 087  while ( position < size )   

  88. 088  {   

  89. 089  position += inChannel.transferTo( position, maxCount, outChannel );   

  90. 090  }   

  91. 091  }   

  92. 092  finally  

  93. 093  {   

  94. 094  if ( inChannel != null )   

  95. 095  {   

  96. 096  inChannel.close();   

  97. 097  }   

  98. 098  if ( outChannel != null )   

  99. 099  {   

  100. 100  outChannel.close();   

  101. 101  }   

  102. 102  }   

  103. 103  }  

  104. 104   

  105. 105 //8. 创建图片的缩略图   

  106. 106 private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)  

  107. 107  throws InterruptedException, FileNotFoundException, IOException   

  108. 108  {   

  109. 109  // load image from filename   

  110. 110  Image image = Toolkit.getDefaultToolkit().getImage(filename);   

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

  112. 112  mediaTracker.addImage(image, 0);   

  113. 113  mediaTracker.waitForID(0);   

  114. 114  // use this to test for errors at this point: System.out.println(mediaTracker.isErrorAny());

  115. 115   

  116. 116  // determine thumbnail size from WIDTH and HEIGHT   

  117. 117  double thumbRatio = (double)thumbWidth / (double)thumbHeight;   

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

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

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

  121. 121  if (thumbRatio < imageRatio) {   

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

  123. 123  } else {   

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

  125. 125  }  

  126. 126   

  127. 127  // draw original image to thumbnail image object and   

  128. 128  // scale it to the new size on-the-fly   

  129. 129  BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);  

  130. 130  Graphics2D graphics2D = thumbImage.createGraphics();   

  131. 131  graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);  

  132. 132  graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);  

  133. 133   

  134. 134  // save thumbnail image to outFilename   

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

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

  137. 137  JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);   

  138. 138  quality = Math.max(0, Math.min(quality, 100));   

  139. 139  param.setQuality((float)quality / 100.0f, false);   

  140. 140  encoder.setJPEGEncodeParam(param);   

  141. 141  encoder.encode(thumbImage);   

  142. 142  out.close();   

  143. 143  }  

  144. 144   

  145. 145 //9. 创建 JSON 格式的数据   

  146. 146 import org.json.JSONObject;   

  147. 147 ...   

  148. 148 ...   

  149. 149 JSONObject json = new JSONObject();   

  150. 150 json.put("city", "Mumbai");   

  151. 151 json.put("country", "India");   

  152. 152 ...   

  153. 153 String output = json.toString();   

  154. 154 ...  

  155. 155   

  156. 156 //10. 使用iText JAR生成PDF   

  157. 157 import java.io.File;   

  158. 158 import java.io.FileOutputStream;   

  159. 159 import java.io.OutputStream;   

  160. 160 import java.util.Date;  

  161. 161   

  162. 162 import com.lowagie.text.Document;   

  163. 163 import com.lowagie.text.Paragraph;   

  164. 164 import com.lowagie.text.pdf.PdfWriter;  

  165. 165   

  166. 166 public class GeneratePDF {  

  167. 167   

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

  169. 169  try {   

  170. 170  OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));  

  171. 171   

  172. 172  Document document = new Document();   

  173. 173  PdfWriter.getInstance(document, file);   

  174. 174  document.open();   

  175. 175  document.add(new Paragraph("Hello Kiran"));   

  176. 176  document.add(new Paragraph(new Date().toString()));  

  177. 177   

  178. 178  document.close();   

  179. 179  file.close();  

  180. 180   

  181. 181  } catch (Exception e) {  

  182. 182   

  183. 183  e.printStackTrace();   

  184. 184  }   

  185. 185  }   

  186. 186 }  

  187. 187   

  188. 188 //11. HTTP 代理设置   

  189. 189 System.getProperties().put("http.proxyHost", "someProxyURL");   

  190. 190 System.getProperties().put("http.proxyPort", "someProxyPort");   

  191. 191 System.getProperties().put("http.proxyUser", "someUserName");   

  192. 192 System.getProperties().put("http.proxyPassword", "somePassword");  

  193. 193   

  194. 194 //12. 单实例Singleton 示例   

  195. 195 public class SimpleSingleton {   

  196. 196  private static SimpleSingleton singleInstance = new SimpleSingleton();  

  197. 197   

  198. 198  //Marking default constructor private   

  199. 199  //to avoid direct instantiation.   

  200. 200  private SimpleSingleton() {   

  201. 201  }  

  202. 202   

  203. 203  //Get instance for class SimpleSingleton   

  204. 204  public static SimpleSingleton getInstance() {  

  205. 205   

  206. 206  return singleInstance;   

  207. 207  }   

  208. 208 }  

  209. 209   

  210. 210 //另一种实现  

  211. 211   

  212. 212 public enum SimpleSingleton {   

  213. 213  INSTANCE;   

  214. 214  public void doSomething() {   

  215. 215  }   

  216. 216 }  

  217. 217   

  218. 218 //Call the method from Singleton:   

  219. 219 SimpleSingleton.INSTANCE.doSomething();  

  220. 220   

  221. 221 //13. 抓屏程序   

  222. 222 import java.awt.Dimension;   

  223. 223 import java.awt.Rectangle;   

  224. 224 import java.awt.Robot;   

  225. 225 import java.awt.Toolkit;   

  226. 226 import java.awt.image.BufferedImage;   

  227. 227 import javax.imageio.ImageIO;   

  228. 228 import java.io.File;  

  229. 229   

  230. 230 ...   

  231. 231 public void captureScreen(String fileName) throws Exception {  

  232. 232   

  233. 233  Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();   

  234. 234  Rectangle screenRectangle = new Rectangle(screenSize);   

  235. 235  Robot robot = new Robot();   

  236. 236  BufferedImage image = robot.createScreenCapture(screenRectangle);   

  237. 237  ImageIO.write(image, "png", new File(fileName));  

  238. 238   

  239. 239 }   

  240. 240 //14. 列出文件和目录   

  241. 241 File dir = new File("directoryName");   

  242. 242  String[] children = dir.list();   

  243. 243  if (children == null) {   

  244. 244  // Either dir does not exist or is not a directory   

  245. 245  } else {   

  246. 246  for (int i=0; i < children.length; i++) {   

  247. 247  // Get filename of file or directory   

  248. 248  String filename = children[i];   

  249. 249  }   

  250. 250  }  

  251. 251   

  252. 252  // It is also possible to filter the list of returned files.   

  253. 253  // This example does not return any files that start with `.’.   

  254. 254  FilenameFilter filter = new FilenameFilter() {   

  255. 255  public boolean accept(File dir, String name) {   

  256. 256  return !name.startsWith(".");   

  257. 257  }   

  258. 258  };   

  259. 259  children = dir.list(filter);  

  260. 260   

  261. 261  // The list of files can also be retrieved as File objects   

  262. 262  File[] files = dir.listFiles();  

  263. 263   

  264. 264  // This filter only returns directories   

  265. 265  FileFilter fileFilter = new FileFilter() {   

  266. 266  public boolean accept(File file) {   

  267. 267  return file.isDirectory();   

  268. 268  }   

  269. 269  };   

  270. 270  files = dir.listFiles(fileFilter);  

  271. 271   

  272. 272 //15. 创建ZIP和JAR文件  

  273. 273   

  274. 274 import java.util.zip.*;   

  275. 275 import java.io.*;  

  276. 276   

  277. 277 public class ZipIt {   

  278. 278  public static void main(String args[]) throws IOException {   

  279. 279  if (args.length < 2) {   

  280. 280  System.err.println("usage: java ZipIt Zip.zip file1 file2 file3");   

  281. 281  System.exit(-1);   

  282. 282  }   

  283. 283  File zipFile = new File(args[0]);   

  284. 284  if (zipFile.exists()) {   

  285. 285  System.err.println("Zip file already exists, please try another");   

  286. 286  System.exit(-2);   

  287. 287  }   

  288. 288  FileOutputStream fos = new FileOutputStream(zipFile);   

  289. 289  ZipOutputStream zos = new ZipOutputStream(fos);   

  290. 290  int bytesRead;   

  291. 291  byte[] buffer = new byte[1024];   

  292. 292  CRC32 crc = new CRC32();   

  293. 293  for (int i=1, n=args.length; i < n; i++) {   

  294. 294  String name = args[i];   

  295. 295  File file = new File(name);   

  296. 296  if (!file.exists()) {   

  297. 297  System.err.println("Skipping: " + name);   

  298. 298  continue;   

  299. 299  }   

  300. 300  BufferedInputStream bis = new BufferedInputStream(   

  301. 301  new FileInputStream(file));   

  302. 302  crc.reset();   

  303. 303  while ((bytesRead = bis.read(buffer)) != -1) {   

  304. 304  crc.update(buffer, 0, bytesRead);   

  305. 305  }   

  306. 306  bis.close();   

  307. 307  // Reset to beginning of input stream   

  308. 308  bis = new BufferedInputStream(   

  309. 309  new FileInputStream(file));   

  310. 310  ZipEntry entry = new ZipEntry(name);   

  311. 311  entry.setMethod(ZipEntry.STORED);   

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

  313. 313  entry.setSize(file.length());   

  314. 314  entry.setCrc(crc.getValue());   

  315. 315  zos.putNextEntry(entry);   

  316. 316  while ((bytesRead = bis.read(buffer)) != -1) {   

  317. 317  zos.write(buffer, 0, bytesRead);   

  318. 318  }   

  319. 319  bis.close();   

  320. 320  }   

  321. 321  zos.close();   

  322. 322  }   

  323. 323 }  

  324. 324   

  325. 325 //16. 解析/读取XML 文件   

  326. 326 XML文件   

  327. 327 <?xml version="1.0"?>   

  328. 328 <students>   

  329. 329  <student>   

  330. 330  <name>John</name>   

  331. 331  <grade>B</grade>   

  332. 332  <age>12</age>   

  333. 333  </student>   

  334. 334  <student>   

  335. 335  <name>Mary</name>   

  336. 336  <grade>A</grade>   

  337. 337  <age>11</age>   

  338. 338  </student>   

  339. 339  <student>   

  340. 340  <name>Simon</name>   

  341. 341  <grade>A</grade>   

  342. 342  <age>18</age>   

  343. 343  </student>   

  344. 344 </students>  

  345. 345   

  346. 346 //Java代码   

  347. 347 package net.viralpatel.java.xmlparser;  

  348. 348   

  349. 349 import java.io.File;   

  350. 350 import javax.xml.parsers.DocumentBuilder;   

  351. 351 import javax.xml.parsers.DocumentBuilderFactory;  

  352. 352   

  353. 353 import org.w3c.dom.Document;   

  354. 354 import org.w3c.dom.Element;   

  355. 355 import org.w3c.dom.Node;   

  356. 356 import org.w3c.dom.NodeList;  

  357. 357   

  358. 358 public class XMLParser {  

  359. 359   

  360. 360  public void getAllUserNames(String fileName) {   

  361. 361  try {   

  362. 362  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();   

  363. 363  DocumentBuilder db = dbf.newDocumentBuilder();   

  364. 364  File file = new File(fileName);   

  365. 365  if (file.exists()) {   

  366. 366  Document doc = db.parse(file);   

  367. 367  Element docEle = doc.getDocumentElement();  

  368. 368   

  369. 369  // Print root element of the document   

  370. 370  System.out.println("Root element of the document: "  

  371. 371  + docEle.getNodeName());  

  372. 372   

  373. 373  NodeList studentList = docEle.getElementsByTagName("student");  

  374. 374   

  375. 375  // Print total student elements in document   

  376. 376  System.out   

  377. 377  .println("Total students: " + studentList.getLength());  

  378. 378   

  379. 379  if (studentList != null && studentList.getLength() > 0) {   

  380. 380  for (int i = 0; i < studentList.getLength(); i++) {  

  381. 381   

  382. 382  Node node = studentList.item(i);  

  383. 383   

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

  385. 385   

  386. 386  System.out   

  387. 387  .println("=====================");  

  388. 388   

  389. 389  Element e = (Element) node;   

  390. 390  NodeList nodeList = e.getElementsByTagName("name");   

  391. 391  System.out.println("Name: "  

  392. 392  + nodeList.item(0).getChildNodes().item(0)   

  393. 393  .getNodeValue());  

  394. 394   

  395. 395  nodeList = e.getElementsByTagName("grade");   

  396. 396  System.out.println("Grade: "  

  397. 397  + nodeList.item(0).getChildNodes().item(0)   

  398. 398  .getNodeValue());  

  399. 399   

  400. 400  nodeList = e.getElementsByTagName("age");   

  401. 401  System.out.println("Age: "  

  402. 402  + nodeList.item(0).getChildNodes().item(0)   

  403. 403  .getNodeValue());   

  404. 404  }   

  405. 405  }   

  406. 406  } else {   

  407. 407  System.exit(1);   

  408. 408  }   

  409. 409  }   

  410. 410  } catch (Exception e) {   

  411. 411  System.out.println(e);   

  412. 412  }   

  413. 413  }   

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

  415. 415   

  416. 416  XMLParser parser = new XMLParser();   

  417. 417  parser.getAllUserNames("c:\\test.xml");   

  418. 418  }   

  419. 419 }   

  420. 420 //17. 把 Array 转换成 Map   

  421. 421 import java.util.Map;   

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

  423. 423   

  424. 424 public class Main {  

  425. 425   

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

  427. 427  String[ ][ ] countries = { { "United States", "New York" }, { "United Kingdom", "London" },  

  428. 428  { "Netherland", "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" } };

  429. 429   

  430. 430  Map countryCapitals = ArrayUtils.toMap(countries);  

  431. 431   

  432. 432  System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));  

  433. 433  System.out.println("Capital of France is " + countryCapitals.get("France"));  

  434. 434  }   

  435. 435 }  

  436. 436   

  437. 437 //18. 发送邮件   

  438. 438 import javax.mail.*;   

  439. 439 import javax.mail.internet.*;   

  440. 440 import java.util.*;  

  441. 441   

  442. 442 public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException  

  443. 443 {   

  444. 444  boolean debug = false;  

  445. 445   

  446. 446  //Set the host smtp address   

  447. 447  Properties props = new Properties();   

  448. 448  props.put("mail.smtp.host", "smtp.example.com");  

  449. 449   

  450. 450  // create some properties and get the default Session   

  451. 451  Session session = Session.getDefaultInstance(props, null);   

  452. 452  session.setDebug(debug);  

  453. 453   

  454. 454  // create a message   

  455. 455  Message msg = new MimeMessage(session);  

  456. 456   

  457. 457  // set the from and to address   

  458. 458  InternetAddress addressFrom = new InternetAddress(from);   

  459. 459  msg.setFrom(addressFrom);  

  460. 460   

  461. 461  InternetAddress[] addressTo = new InternetAddress[recipients.length];   

  462. 462  for (int i = 0; i < recipients.length; i++)   

  463. 463  {   

  464. 464  addressTo[i] = new InternetAddress(recipients[i]);   

  465. 465  }   

  466. 466  msg.setRecipients(Message.RecipientType.TO, addressTo);  

  467. 467   

  468. 468  // Optional : You can also set your custom headers in the Email if you Want  

  469. 469  msg.addHeader("MyHeaderName", "myHeaderValue");  

  470. 470   

  471. 471  // Setting the Subject and Content Type   

  472. 472  msg.setSubject(subject);   

  473. 473  msg.setContent(message, "text/plain");   

  474. 474  Transport.send(msg);   

  475. 475 }  

  476. 476   

  477. 477 //19. 发送代数据的HTTP 请求   

  478. 478 import java.io.BufferedReader;   

  479. 479 import java.io.InputStreamReader;   

  480. 480 import java.net.URL;  

  481. 481   

  482. 482 public class Main {   

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

  484. 484  try {   

  485. 485  URL my_url = new URL("http://cocre.com/");   

  486. 486  BufferedReader br = new BufferedReader(new InputStreamReader(my_url.openStream()));  

  487. 487  String strTemp = "";   

  488. 488  while(null != (strTemp = br.readLine())){   

  489. 489  System.out.println(strTemp);   

  490. 490  }   

  491. 491  } catch (Exception ex) {   

  492. 492  ex.printStackTrace();   

  493. 493  }   

  494. 494  }   

  495. 495 }  

  496. 496   

  497. 497 //20. 改变数组的大小   

  498. 498 /**   

  499. 499 * Reallocates an array with a new size, and copies the contents   

  500. 500 * of the old array to the new array.   

  501. 501 * @param oldArray the old array, to be reallocated.   

  502. 502 * @param newSize the new array size.   

  503. 503 * @return A new array with the same contents.   

  504. 504 */  

  505. 505 private static Object resizeArray (Object oldArray, int newSize) {   

  506. 506  int oldSize = java.lang.reflect.Array.getLength(oldArray);   

  507. 507  Class elementType = oldArray.getClass().getComponentType();   

  508. 508  Object newArray = java.lang.reflect.Array.newInstance(   

  509. 509  elementType,newSize);   

  510. 510  int preserveLength = Math.min(oldSize,newSize);   

  511. 511  if (preserveLength > 0)   

  512. 512  System.arraycopy (oldArray,0,newArray,0,preserveLength);   

  513. 513  return newArray;   

  514. 514 }  

  515. 515   

  516. 516 // Test routine for resizeArray().   

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

  518. 518  int[] a = {1,2,3};   

  519. 519  a = (int[])resizeArray(a,5);   

  520. 520  a[3] = 4;   

  521. 521  a[4] = 5;   

  522. 522  for (int i=0; i<a.length; i++)   

  523. 523  System.out.println (a[i]);   

  524. 524 }
复制代码

论坛徽章:
0
2 [报告]
发表于 2012-03-15 20:57 |只看该作者
谢谢分享
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP