Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 1010|回复: 0

java软件工程师必备的20个java代码(后10)

[复制链接]

该用户从未签到

发表于 2011-7-26 22:47:11 | 显示全部楼层 |阅读模式
11. 在java上的HTTP代理设置
  1. System.getProperties().put("http.proxyHost",
  2. "someProxyURL");   
  3. System.getProperties().put("http.proxyPort",
  4. "someProxyPort");   
  5. System.getProperties().put("http.proxyUser",
  6. "someUserName");   
  7. System.getProperties().put("http.proxyPassword",
  8. "somePassword");
  9. System.getProperties().put("http.proxyHost",
  10. "someProxyURL");
  11. System.getProperties().put("http.proxyPort",
  12. "someProxyPort");
  13. System.getProperties().put("http.proxyUser",
  14. "someUserName");
  15. System.getProperties().put("http.proxyPassword",
  16. "somePassword");
复制代码

12. java Singleton 例子
  1. Read this article for more
  2. details.
  3. Update: Thanks Markus for the comment. I have updated the code and
  4. changed it to
  5. more robust implementation.
  6. public class SimpleSingleton {   
  7. private static SimpleSingleton singleInstance =  new SimpleSingleton
  8. ();   
  9. //Marking default constructor
  10. private   
  11. //to avoid direct
  12. instantiation.   
  13. private SimpleSingleton()
  14. {   
  15. }   
  16. //Get instance for class SimpleSingleton   
  17. public static SimpleSingleton getInstance() {   
  18. return
  19. singleInstance;   
  20. }   
  21. }
  22. public class SimpleSingleton {
  23. private static SimpleSingleton
  24. singleInstance =  new SimpleSingleton();
  25. //Marking default constructor private
  26. //to avoid direct
  27. instantiation.
  28. private SimpleSingleton() {
  29. }
  30. //Get instance for class SimpleSingleton
  31. public static
  32. SimpleSingleton getInstance() {
  33. return singleInstance;
  34. }
  35. }
  36. One more implementation of
  37. Singleton class. Thanks to Ralph and Lukasz Zielinski
  38. for pointing this out.
  39. public enum SimpleSingleton {   
  40. INSTANCE;   
  41. public void doSomething()
  42. {   
  43. }   
  44. }   
  45. //Call the method from Singleton:   
  46. SimpleSingleton.INSTANCE.doSomething();
  47. public enum SimpleSingleton {
  48. INSTANCE;
  49. public void
  50. doSomething() {
  51. }
  52. }
  53. //Call the method from Singleton:
  54. SimpleSingleton.INSTANCE.doSomething();
复制代码

13. 在java上做屏幕截图
  1. Read this article for more details.
  2. import
  3. 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
  9. javax.imageio.ImageIO;   
  10. import java.io.File;   
  11. ...   
  12. public void captureScreen(String fileName)
  13. throws Exception {   
  14. Dimension screenSize =
  15. Toolkit.getDefaultToolkit().getScreenSize();   
  16. Rectangle
  17. screenRectangle = new Rectangle(screenSize);   
  18. Robot
  19. robot = new Robot();   
  20. BufferedImage image =
  21. robot.createScreenCapture(screenRectangle);   
  22. ImageIO.write(image, "png", new File(fileName));   
  23. }
  24.    
  25. ...
  26. import java.awt.Dimension;
  27. import java.awt.Rectangle;
  28. import
  29. java.awt.Robot;
  30. import java.awt.Toolkit;
  31. import
  32. java.awt.image.BufferedImage;
  33. import javax.imageio.ImageIO;
  34. import
  35. java.io.File;
  36. ...
  37. public void captureScreen(String fileName) throws Exception {
  38. Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize
  39. ();
  40. Rectangle screenRectangle = new Rectangle
  41. (screenSize);
  42. Robot robot = new Robot();
  43. BufferedImage image = robot.createScreenCapture(screenRectangle);
  44. ImageIO.write(image, "png", new File(fileName));
  45. }
  46. ...
复制代码

14. 在java中的文件,目录列表
  1. File dir = new File("directoryName");   
  2. String[] children = dir.list();   
  3. if (children ==
  4. null) {   
  5. // Either dir does not exist
  6. or is not a directory   
  7. } else {   
  8. for (int i=0; i < children.length; i++)
  9. {   
  10. // Get
  11. filename of file or directory   
  12. String filename =
  13. children;   
  14. }   
  15. }   
  16. // It is also possible to filter the
  17. list of returned files.   
  18. // This example does not return any
  19. files that start with `.'.   
  20. FilenameFilter filter = new
  21. FilenameFilter() {   
  22. public boolean
  23. accept(File dir, String name) {   
  24. return !name.startsWith
  25. (".");   
  26. }   
  27. };   
  28. children = dir.list(filter);   
  29. // The list of files can also be retrieved as File objects   
  30. File[] files = dir.listFiles();   
  31. //
  32. This filter only returns directories   
  33. FileFilter fileFilter =
  34. new FileFilter() {   
  35. public boolean
  36. accept(File file) {   
  37. return file.isDirectory
  38. ();   
  39. }   
  40. };   
  41. files = dir.listFiles(fileFilter);
  42. File dir = new File("directoryName");
  43. String[]
  44. children = dir.list();
  45. if (children == null)
  46. {
  47. // Either dir does not exist or is
  48. not a directory
  49. } else
  50. {
  51. for (int i=0; i <
  52. children.length; i++)
  53. {
  54. // Get
  55. filename of file or
  56. directory
  57. String filename = children;
  58. }
  59. }
  60. // It is also possible to filter the list of returned
  61. files.
  62. // This example does not return any files that start
  63. with `.'.
  64. FilenameFilter filter = new FilenameFilter()
  65. {
  66. public boolean accept(File dir,
  67. String name)
  68. {
  69. return !
  70. name.startsWith(".");
  71. }
  72. };
  73. children = dir.list(filter);
  74. // The list of files can also be retrieved as File
  75. objects
  76. File[] files = dir.listFiles();
  77. // This filter only returns directories
  78. FileFilter fileFilter = new FileFilter()
  79. {
  80. public boolean accept(File file)
  81. {
  82. return
  83. file.isDirectory();
  84. }
  85. };
  86. files = dir.listFiles
  87. (fileFilter);
复制代码


15. 在java中创建ZIP和JAR文件
  1. import java.util.zip.*;   
  2. import
  3. java.io.*;   
  4. public class ZipIt {   
  5. public static void main(String args[]) throws IOException
  6. {   
  7. if (args.length <
  8. 2) {   
  9. System.err.println("usage: java ZipIt Zip.zip file1 file2 file3");   
  10. System.exit
  11. (-1);   
  12. }   
  13. File zipFile = new File(args
  14. [0]);   
  15. if
  16. (zipFile.exists()) {   
  17. System.err.println("Zip file already exists, please try another");   
  18. System.exit
  19. (-2);   
  20. }   
  21. FileOutputStream fos = new
  22. FileOutputStream(zipFile);   
  23. ZipOutputStream zos = new
  24. ZipOutputStream(fos);   
  25. int bytesRead;   
  26. byte[]
  27. buffer = new byte[1024];   
  28. CRC32 crc = new CRC32();   
  29. for (int i=1, n=args.length; i < n; i++) {   
  30. String name
  31. = args;   
  32. File file =
  33. new File(name);   
  34. if (!
  35. file.exists()) {   
  36. &
  37. nbsp;  System.err.println("Skipping: " + name);   
  38. &
  39. nbsp;  continue;   
  40. }
  41.    
  42. BufferedInputStream bis = new BufferedInputStream(   
  43. &
  44. nbsp;  new FileInputStream(file));   
  45. crc.reset
  46. ();   
  47. while
  48. ((bytesRead = bis.read(buffer)) != -1) {   
  49. &
  50. nbsp;  crc.update(buffer, 0, bytesRead);   
  51. }
  52.    
  53. bis.close();   
  54. // Reset to
  55. beginning of input stream   
  56. bis = new
  57. BufferedInputStream(   
  58. &
  59. nbsp;  new FileInputStream(file));   
  60. ZipEntry
  61. entry = new ZipEntry(name);   
  62. entry.setMethod(ZipEntry.STORED);   
  63. entry.setCompressedSize(file.length());   
  64. entry.setSize(file.length());   
  65. entry.setCrc(crc.getValue());   
  66. zos.putNextEntry(entry);   
  67. while
  68. ((bytesRead = bis.read(buffer)) != -1) {   
  69. &
  70. nbsp;  zos.write(buffer, 0, bytesRead);   
  71. }
  72.    
  73. bis.close();   
  74. }
  75.    
  76. zos.close
  77. ();   
  78. }   
  79. }
  80. import java.util.zip.*;
  81. import java.io.*;
  82. public class ZipIt {
  83. public static void main(String args
  84. []) throws IOException {
  85. if
  86. (args.length < 2)
  87. {
  88. System.err.println("usage: java ZipIt Zip.zip file1 file2
  89. file3");
  90. System.exit(-1);
  91. }
  92. File zipFile = new File(args
  93. [0]);
  94. if (zipFile.exists())
  95. {
  96. System.err.println("Zip file already exists, please try
  97. another");
  98. System.exit(-2);
  99. }
  100. FileOutputStream fos = new
  101. FileOutputStream(zipFile);
  102. ZipOutputStream zos = new ZipOutputStream
  103. (fos);
  104. int
  105. bytesRead;
  106. byte[] buffer = new byte
  107. [1024];
  108. CRC32 crc = new CRC32
  109. ();
  110. for (int i=1, n=args.length; i
  111. < n; i++)
  112. {
  113. String name
  114. = args;
  115. File file = new File
  116. (name);
  117. if
  118. (!file.exists())
  119. {
  120.    System.err.println("Skipping: " +
  121. name);
  122. &
  123. nbsp;   
  124. continue;
  125. }
  126. BufferedInputStream bis = new BufferedInputStream
  127. (
  128.    new FileInputStream
  129. (file));
  130. crc.reset();
  131. while ((bytesRead = bis.read(buffer)) != -1)
  132. {
  133.    crc.update(buffer, 0,
  134. bytesRead);
  135. }
  136. bis.close
  137. ();
  138. // Reset
  139. to beginning of input
  140. stream
  141. bis =
  142. new BufferedInputStream
  143. (
  144.    new FileInputStream
  145. (file));
  146. ZipEntry entry = new ZipEntry
  147. (name);
  148. entry.setMethod
  149. (ZipEntry.STORED);
  150. &
  151. nbsp; entry.setCompressedSize(file.length
  152. ());
  153. entry.setSize(file.length
  154. ());
  155. entry.setCrc(crc.getValue
  156. ());
  157. zos.putNextEntry
  158. (entry);
  159. while ((bytesRead = bis.read(buffer)) != -1)
  160. {
  161.    zos.write(buffer, 0,
  162. bytesRead);
  163. }
  164. bis.close
  165. ();
  166. }
  167. zos.close();
  168. }
  169. }
  170. 16. Parsing / Reading XML file in java
  171. Sample XML file.
  172. John
  173. B
  174. 12
  175. Mary
  176. A
  177. 11
  178. Simon
  179. A
  180. 18
  181. John
  182. B
  183. 12
  184. Mary
  185. A
  186. <
  187. AGE>11
  188. Simon
  189. A
  190. 18
  191. java code to parse above XML.
  192. package net.viralpatel.java.xmlparser;   
  193. import java.io.File;   
  194. import
  195. javax.xml.parsers.DocumentBuilder;   
  196. import
  197. javax.xml.parsers.DocumentBuilderFactory;   
  198. import
  199. org.w3c.dom.Document;   
  200. import org.w3c.dom.Element;   
  201. import org.w3c.dom.Node;   
  202. import
  203. org.w3c.dom.NodeList;   
  204. public class XMLParser
  205. {   
  206. public void getAllUserNames(String
  207. fileName) {   
  208. try
  209. {   
  210. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();   
  211. DocumentBuilder db = dbf.newDocumentBuilder();   
  212. File file =
  213. new File(fileName);   
  214. if
  215. (file.exists()) {   
  216. &
  217. nbsp;  Document doc = db.parse(file);   
  218. &
  219. nbsp;  Element docEle = doc.getDocumentElement();   
  220. &
  221. nbsp;  // Print root element of the document   
  222. &
  223. nbsp;  System.out.println("Root element of the document: "
  224. &
  225. nbsp;          + docEle.getNodeName
  226. ());   
  227. &
  228. nbsp;  NodeList studentList = docEle.getElementsByTagName
  229. ("student");   
  230. &
  231. nbsp;  // Print total student elements in document   
  232. &
  233. nbsp;  System.out   
  234. &
  235. nbsp;          .println("Total
  236. students: " + studentList.getLength());   
  237. &
  238. nbsp;  if (studentList != null && studentList.getLength() > 0)
  239. {   
  240. &
  241. nbsp;      for (int i = 0; i < studentList.getLength();
  242. i++) {   
  243. &
  244. nbsp;          Node node =
  245. studentList.item(i);   
  246. &
  247. nbsp;          if (node.getNodeType()
  248. == Node.ELEMENT_NODE) {   
  249. &
  250. nbsp;            
  251. System.out   
  252. &
  253. nbsp;            
  254.          .println
  255. ("=====================");   
  256. &
  257. nbsp;            
  258. Element e = (Element) node;   
  259. &
  260. nbsp;            
  261. NodeList nodeList = e.getElementsByTagName("name");   
  262. &
  263. nbsp;            
  264. System.out.println("Name: "
  265. &
  266. nbsp;            
  267.          + nodeList.item(0).getChildNodes
  268. ().item(0)   
  269. &
  270. nbsp;            
  271.                
  272. ;   .getNodeValue());   
  273. &
  274. nbsp;            
  275. nodeList = e.getElementsByTagName("grade");   
  276. &
  277. nbsp;            
  278. System.out.println("Grade: "
  279. &
  280. nbsp;            
  281.          + nodeList.item(0).getChildNodes
  282. ().item(0)   
  283. &
  284. nbsp;            
  285.                
  286. ;   .getNodeValue());   
  287. &
  288. nbsp;            
  289. nodeList = e.getElementsByTagName("age");   
  290. &
  291. nbsp;            
  292. System.out.println("Age: "
  293. &
  294. nbsp;            
  295.          + nodeList.item(0).getChildNodes
  296. ().item(0)   
  297. &
  298. nbsp;            
  299.                
  300. ;   .getNodeValue());   
  301. &
  302. nbsp;          }   
  303. &
  304. nbsp;      }   
  305. &
  306. nbsp;  } else {   
  307. &
  308. nbsp;      System.exit(1);   
  309. &
  310. nbsp;  }   
  311. }
  312.    
  313. } catch (Exception e)
  314. {   
  315. System.out.println(e);   
  316. }   
  317. }   
  318. public
  319. static void main(String[] args) {   
  320. XMLParser parser = new XMLParser
  321. ();   
  322. parser.getAllUserNames("c:\\test.xml");   
  323. }
  324.    
  325. }
  326. package net.viralpatel.java.xmlparser;
  327. import java.io.File;
  328. import javax.xml.parsers.DocumentBuilder;
  329. import
  330. javax.xml.parsers.DocumentBuilderFactory;
  331. import org.w3c.dom.Document;
  332. import org.w3c.dom.Element;
  333. import
  334. org.w3c.dom.Node;
  335. import org.w3c.dom.NodeList;
  336. public class XMLParser {
  337. public void getAllUserNames(String fileName) {
  338. try
  339. {
  340. DocumentBuilderFactory dbf =
  341. DocumentBuilderFactory.newInstance();
  342. DocumentBuilder db =
  343. dbf.newDocumentBuilder();
  344. File file = new File
  345. (fileName);
  346. if (file.exists())
  347. {
  348. Document doc = db.parse
  349. (file);
  350. Element docEle = doc.getDocumentElement();
  351. // Print root element of the
  352. document
  353. System.out.println("Root element of the
  354. document: "
  355. + docEle.getNodeName());
  356. NodeList studentList = docEle.getElementsByTagName
  357. ("student");
  358. // Print total student elements in
  359. document
  360. System.out
  361. &nb
  362. sp;.println("Total students: " +
  363. studentList.getLength());
  364. if (studentList != null &&
  365. studentList.getLength()
  366. > 0) {
  367. for (int i = 0; i <
  368. studentList.getLength
  369. (); i++) {
  370. Node node = studentList.item(i);
  371. if (node.getNodeType() ==
  372. Node.ELEMENT_NODE) {
  373. System.out
  374.      .println
  375. ("=====================");
  376. Element e = (Element)
  377. node;
  378. NodeList nodeList =
  379. e.getElementsByTagName
  380. ("name");
  381. System.out.println("Name:
  382. "
  383. +
  384. nodeList.item(0).getChildNodes().item(0)
  385. .getNodeValue());
  386. nodeList =
  387. e.getElementsByTagName
  388. ("grade");
  389. System.out.println("Grade:
  390. "
  391. +
  392. nodeList.item(0).getChildNodes().item(0)
  393. .getNodeValue());
  394. nodeList =
  395. e.getElementsByTagName
  396. ("age");
  397. System.out.println("Age:
  398. "
  399. +
  400. nodeList.item(0).getChildNodes().item(0)
  401. .getNodeValue());
  402. }
  403. }
  404. } else
  405. {
  406. System.exit(1);
  407. }
  408. }
  409. } catch (Exception e)
  410. {
  411. System.out.println(e);
  412. }
  413. }
  414. public static void main(String[] args) {
  415. XMLParser parser = new XMLParser
  416. ();
  417. parser.getAllUserNames("c:\\test.xml");
  418. }
  419. }
  420. 17.
  421. Convert Array to Map in java
  422. import java.util.Map;   
  423. import
  424. org.apache.commons.lang.ArrayUtils;   
  425. public class Main
  426. {   
  427. public static void main(String[] args)
  428. {   
  429. String[][] countries = { { "United States",
  430. "New York" }, { "United Kingdom",
  431. "London" },   
  432. {
  433. "Netherland", "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" }
  434. };   
  435. Map countryCapitals =
  436. ArrayUtils.toMap(countries);   
  437. System.out.println("Capital of Japan is " + countryCapitals.get
  438. ("Japan"));   
  439. System.out.println("Capital of
  440. France is " + countryCapitals.get("France"));   
  441. }   
  442. }
  443. import java.util.Map;
  444. import org.apache.commons.lang.ArrayUtils;
  445. public class Main {
  446. public static void main(String[] args) {
  447. String[][]
  448. countries = { { "United States", "New York" }, { "United Kingdom",
  449. "London" },
  450. { "Netherland",
  451. "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" }
  452. };
  453. Map countryCapitals = ArrayUtils.toMap(countries);
  454. System.out.println("Capital of Japan is " +
  455. countryCapitals.get("Japan"));
  456. System.out.println("Capital of
  457. France is " + countryCapitals.get("France"));
  458. }
  459. }
  460. 18. Send Email
  461. using java
  462. import javax.mail.*;   
  463. import
  464. javax.mail.internet.*;   
  465. import java.util.*;   
  466. public void postMail( String recipients[ ], String subject, String message ,
  467. String
  468. from) throws MessagingException   
  469. {   
  470. boolean debug = false;   
  471. //Set the host smtp address   
  472. Properties props = new Properties();   
  473. props.put("mail.smtp.host",
  474. "smtp.example.com");   
  475. // create some
  476. properties and get the default Session   
  477. Session
  478. session = Session.getDefaultInstance(props, null);   
  479. session.setDebug(debug);   
  480. // create a message   
  481. Message msg = new MimeMessage(session);   
  482. // set the from and to address   
  483. InternetAddress addressFrom = new InternetAddress
  484. (from);   
  485. msg.setFrom(addressFrom);   
  486. InternetAddress[] addressTo = new
  487. InternetAddress[recipients.length];   
  488. for (int i =
  489. 0; i < recipients.length; i++)   
  490. {   
  491. addressTo = new InternetAddress
  492. (recipients);   
  493. }   
  494. msg.setRecipients(Message.RecipientType.TO,
  495. addressTo);   
  496. // Optional : You can
  497. also set your custom headers in the Email if you Want   
  498. msg.addHeader("MyHeaderName", "myHeaderValue");   
  499. // Setting the Subject and Content
  500. Type   
  501. msg.setSubject(subject);   
  502. msg.setContent(message, "text/plain");   
  503. Transport.send(msg);   
  504. }
  505. import javax.mail.*;
  506. import javax.mail.internet.*;
  507. import
  508. java.util.*;
  509. public void postMail( String recipients[ ], String subject, String message ,
  510. String
  511. from) throws MessagingException
  512. {
  513. boolean debug =
  514. false;
  515. //Set the host smtp address
  516. Properties props = new Properties();
  517. props.put
  518. ("mail.smtp.host", "smtp.example.com");
  519. // create some properties and get the default
  520. Session
  521. Session session = Session.getDefaultInstance(props,
  522. null);
  523. session.setDebug(debug);
  524. // create a message
  525. Message msg = new
  526. MimeMessage(session);
  527. // set the from and to address
  528. InternetAddress addressFrom = new InternetAddress(from);
  529. msg.setFrom(addressFrom);
  530. InternetAddress[] addressTo = new InternetAddress
  531. [recipients.length];
  532. for (int i = 0; i <
  533. recipients.length; i++)
  534. {
  535. addressTo = new InternetAddress
  536. (recipients);
  537. }
  538. msg.setRecipients
  539. (Message.RecipientType.TO, addressTo);
  540. // Optional : You can also set your custom headers in the
  541. Email if you Want
  542. msg.addHeader("MyHeaderName",
  543. "myHeaderValue");
  544. // Setting the Subject and Content Type
  545. msg.setSubject(subject);
  546. msg.setContent(message,
  547. "text/plain");
  548. Transport.send(msg);
  549. }
  550. 19. Send HTTP
  551. request & fetching data using java
  552. import java.io.BufferedReader;   
  553. import
  554. java.io.InputStreamReader;   
  555. import java.net.URL;   
  556. public class Main {   
  557. public static
  558. void main(String[] args)  {   
  559. try {   
  560. URL my_url =
  561. new URL("http://www.viralpatel.net/blogs/");&nbs
  562. p;
  563. BufferedReader br = new BufferedReader(new InputStreamReader
  564. (my_url.openStream()));   
  565. String
  566. strTemp = "";   
  567. while(null
  568. != (strTemp = br.readLine())){   
  569. System.out.println(strTemp);   
  570. }   
  571. } catch (Exception ex) {   
  572. ex.printStackTrace();   
  573. }
  574.    
  575. }   
  576. }
  577. import java.io.BufferedReader;
  578. import
  579. java.io.InputStreamReader;
  580. import java.net.URL;
  581. public class Main {
  582. public static void main(String[] args)
  583. {
  584. try {
  585. URL my_url = new URL("http://www.viralpatel.net/blogs/");
  586.    BufferedReader br = new BufferedReader(new
  587. InputStreamReader(my_url.openStream()));
  588. String strTemp =
  589. "";
  590. while(null != (strTemp = br.readLine()))
  591. {
  592. System.out.println(strTemp);
  593. }
  594. } catch (Exception ex) {
  595. ex.printStackTrace
  596. ();
  597. }
  598. }
  599. }
  600. 20. Resize an Array in java
  601. /**
  602. * Reallocates an array with a new size, and copies the
  603. contents
  604. * of the old array to the new array.
  605. * @param
  606. oldArray  the old array, to be reallocated.
  607. * @param
  608. newSize   the new array size.
  609. *
  610. @return          A new array with the
  611. same contents.
  612. */
  613. private static Object resizeArray (Object
  614. oldArray, int newSize) {   
  615. int ldSize =
  616. java.lang.reflect.Array.getLength(oldArray);   
  617. Class
  618. elementType = oldArray.getClass().getComponentType();   
  619. Object newArray = java.lang.reflect.Array.newInstance(   
  620. elementType,newSize);   
  621. int preserveLength = Math.min
  622. (oldSize,newSize);   
  623. if (preserveLength > 0)
  624.    
  625. System.arraycopy
  626. (oldArray,0,newArray,0,preserveLength);   
  627. return
  628. newArray;   
  629. }   
  630. // Test routine for
  631. resizeArray().   
  632. public static void main (String[] args)
  633. {   
  634. int[] a = {1,2,3};   
  635. a =
  636. (int[])resizeArray(a,5);   
  637. a[3] = 4;   
  638. a[4] = 5;   
  639. for (int i=0; i
  640.       System.out.println (a);   
  641. }   
复制代码
16. 在java中解析/读取XML文件
  1. view plaincopy to clipboardprint?
  2. <?xml version="1.0"?>
  3. <students>
  4. <student>
  5. <name>John</name>
  6. <grade>B</grade>
  7. <age>12</age>
  8. </student>
  9. <student>
  10. <name>Mary</name>
  11. <grade>A</grade>
  12. <age>11</age>
  13. </student>
  14. <student>
  15. <name>Simon</name>
  16. <grade>A</grade>
  17. <age>18</age>
  18. </student>
  19. </students>
  20. <?xml version="1.0"?>
  21. <students>
  22. <student>
  23. <name>John</name>
  24. <grade>B</grade>
  25. <age>12</age>
  26. </student>
  27. <student>
  28. <name>Mary</name>
  29. <grade>A</grade>
  30. <age>11</age>
  31. </student>
  32. <student>
  33. <name>Simon</name>
  34. <grade>A</grade>
  35. <age>18</age>
  36. </student>
  37. </students>
  38. java code to parse above XML.
  39. view plaincopy to clipboardprint?
  40. package net.viralpatel.java.xmlparser;   
  41. import java.io.File;   
  42. import javax.xml.parsers.DocumentBuilder;   
  43. import javax.xml.parsers.DocumentBuilderFactory;   
  44. import org.w3c.dom.Document;   
  45. import org.w3c.dom.Element;   
  46. import org.w3c.dom.Node;   
  47. import org.w3c.dom.NodeList;   
  48. public class XMLParser {   
  49. public void getAllUserNames(String fileName) {   
  50. try {   
  51. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();   
  52. DocumentBuilder db = dbf.newDocumentBuilder();   
  53. File file = new File(fileName);   
  54. if (file.exists()) {   
  55. Document doc = db.parse(file);   
  56. Element docEle = doc.getDocumentElement();   
  57. // Print root element of the document   
  58. System.out.println("Root element of the document: "
  59. + docEle.getNodeName());   
  60. NodeList studentList = docEle.getElementsByTagName("student");   
  61. // Print total student elements in document   
  62. System.out   
  63. .println("Total students: " + studentList.getLength());   
  64. if (studentList != null && studentList.getLength() > 0) {   
  65. for (int i = 0; i < studentList.getLength(); i++) {   
  66. Node node = studentList.item(i);   
  67. if (node.getNodeType() == Node.ELEMENT_NODE) {   
  68. System.out   
  69. .println("=====================");   
  70. Element e = (Element) node;   
  71. NodeList nodeList = e.getElementsByTagName("name");   
  72. System.out.println("Name: "
  73. + nodeList.item(0).getChildNodes().item(0)   
  74. .getNodeValue());   
  75. nodeList = e.getElementsByTagName("grade");   
  76. System.out.println("Grade: "
  77. + nodeList.item(0).getChildNodes().item(0)   
  78. .getNodeValue());   
  79. nodeList = e.getElementsByTagName("age");   
  80. System.out.println("Age: "
  81. + nodeList.item(0).getChildNodes().item(0)   
  82. .getNodeValue());   
  83. }   
  84. }   
  85. } else {   
  86. System.exit(1);   
  87. }   
  88. }   
  89. } catch (Exception e) {   
  90. System.out.println(e);   
  91. }   
  92. }   
  93. public static void main(String[] args) {   
  94. XMLParser parser = new XMLParser();   
  95. parser.getAllUserNames("c:\\test.xml");   
  96. }   
  97. }
  98. package net.viralpatel.java.xmlparser;
  99. import java.io.File;
  100. import javax.xml.parsers.DocumentBuilder;
  101. import javax.xml.parsers.DocumentBuilderFactory;
  102. import org.w3c.dom.Document;
  103. import org.w3c.dom.Element;
  104. import org.w3c.dom.Node;
  105. import org.w3c.dom.NodeList;
  106. public class XMLParser {
  107. public void getAllUserNames(String fileName) {
  108. try {
  109. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  110. DocumentBuilder db = dbf.newDocumentBuilder();
  111. File file = new File(fileName);
  112. if (file.exists()) {
  113. Document doc = db.parse(file);
  114. Element docEle = doc.getDocumentElement();
  115. // Print root element of the document
  116. System.out.println("Root element of the document: "
  117. + docEle.getNodeName());
  118. NodeList studentList = docEle.getElementsByTagName("student");
  119. // Print total student elements in document
  120. System.out
  121. .println("Total students: " + studentList.getLength());
  122. if (studentList != null && studentList.getLength() > 0) {
  123. for (int i = 0; i < studentList.getLength(); i++) {
  124. Node node = studentList.item(i);
  125. if (node.getNodeType() == Node.ELEMENT_NODE) {
  126. System.out
  127. .println("=====================");
  128. Element e = (Element) node;
  129. NodeList nodeList = e.getElementsByTagName("name");
  130. System.out.println("Name: "
  131. + nodeList.item(0).getChildNodes().item(0)
  132. .getNodeValue());
  133. nodeList = e.getElementsByTagName("grade");
  134. System.out.println("Grade: "
  135. + nodeList.item(0).getChildNodes().item(0)
  136. .getNodeValue());
  137. nodeList = e.getElementsByTagName("age");
  138. System.out.println("Age: "
  139. + nodeList.item(0).getChildNodes().item(0)
  140. .getNodeValue());
  141. }
  142. }
  143. } else {
  144. System.exit(1);
  145. }
  146. }
  147. } catch (Exception e) {
  148. System.out.println(e);
  149. }
  150. }
  151. public static void main(String[] args) {
  152. XMLParser parser = new XMLParser();
  153. parser.getAllUserNames("c:\\test.xml");
  154. }
  155. }
复制代码


17. 在java中将Array转换成Map
  1. view plaincopy to clipboardprint?
  2. import java.util.Map;   
  3. import org.apache.commons.lang.ArrayUtils;   
  4. public class Main {   
  5. public static void main(String[] args) {   
  6. String[][] countries = { { "United States", "New York" }, { "United Kingdom", "London" },   
  7. { "Netherland", "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" } };   
  8. Map countryCapitals = ArrayUtils.toMap(countries);   
  9. System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));   
  10. System.out.println("Capital of France is " + countryCapitals.get("France"));   
  11. }   
  12. }
  13. import java.util.Map;
  14. import org.apache.commons.lang.ArrayUtils;
  15. public class Main {
  16. public static void main(String[] args) {
  17. String[][] countries = { { "United States", "New York" }, { "United Kingdom", "London" },
  18. { "Netherland", "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" } };
  19. Map countryCapitals = ArrayUtils.toMap(countries);
  20. System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));
  21. System.out.println("Capital of France is " + countryCapitals.get("France"));
  22. }
  23. }
复制代码


18. 在java中发送电子邮件
  1. view plaincopy to clipboardprint?
  2. import javax.mail.*;   
  3. import javax.mail.internet.*;   
  4. import java.util.*;   
  5. public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException   
  6. {   
  7. boolean debug = false;   
  8. //Set the host smtp address   
  9. Properties props = new Properties();   
  10. props.put("mail.smtp.host", "smtp.example.com");   
  11. // create some properties and get the default Session   
  12. Session session = Session.getDefaultInstance(props, null);   
  13. session.setDebug(debug);   
  14. // create a message   
  15. Message msg = new MimeMessage(session);   
  16. // set the from and to address   
  17. InternetAddress addressFrom = new InternetAddress(from);   
  18. msg.setFrom(addressFrom);   
  19. InternetAddress[] addressTo = new InternetAddress[recipients.length];   
  20. for (int i = 0; i < recipients.length; i++)   
  21. {   
  22. addressTo = new InternetAddress(recipients);   
  23. }   
  24. msg.setRecipients(Message.RecipientType.TO, addressTo);   
  25. // Optional : You can also set your custom headers in the Email if you Want   
  26. msg.addHeader("MyHeaderName", "myHeaderValue");   
  27. // Setting the Subject and Content Type   
  28. msg.setSubject(subject);   
  29. msg.setContent(message, "text/plain");   
  30. Transport.send(msg);   
  31. }
  32. import javax.mail.*;
  33. import javax.mail.internet.*;
  34. import java.util.*;
  35. public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException
  36. {
  37. boolean debug = false;
  38. //Set the host smtp address
  39. Properties props = new Properties();
  40. props.put("mail.smtp.host", "smtp.example.com");
  41. // create some properties and get the default Session
  42. Session session = Session.getDefaultInstance(props, null);
  43. session.setDebug(debug);
  44. // create a message
  45. Message msg = new MimeMessage(session);
  46. // set the from and to address
  47. InternetAddress addressFrom = new InternetAddress(from);
  48. msg.setFrom(addressFrom);
  49. InternetAddress[] addressTo = new InternetAddress[recipients.length];
  50. for (int i = 0; i < recipients.length; i++)
  51. {
  52. addressTo = new InternetAddress(recipients);
  53. }
  54. msg.setRecipients(Message.RecipientType.TO, addressTo);
  55. // Optional : You can also set your custom headers in the Email if you Want
  56. msg.addHeader("MyHeaderName", "myHeaderValue");
  57. // Setting the Subject and Content Type
  58. msg.setSubject(subject);
  59. msg.setContent(message, "text/plain");
  60. Transport.send(msg);
  61. }
复制代码

19. 使用java发送HTTP请求和提取数据
  1. view plaincopy to clipboardprint?
  2. import java.io.BufferedReader;   
  3. import java.io.InputStreamReader;   
  4. import java.net.URL;   
  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. }
  19. import java.io.BufferedReader;
  20. import java.io.InputStreamReader;
  21. import java.net.URL;
  22. public class Main {
  23. public static void main(String[] args)  {
  24. try {
  25. URL my_url = new URL("http://www.viralpatel.net/blogs/");
  26. BufferedReader br = new BufferedReader(new InputStreamReader(my_url.openStream()));
  27. String strTemp = "";
  28. while(null != (strTemp = br.readLine())){
  29. System.out.println(strTemp);
  30. }
  31. } catch (Exception ex) {
  32. ex.printStackTrace();
  33. }
  34. }
  35. }
复制代码

20. 在java中调整数组
  1. view plaincopy to clipboardprint?
  2. /**
  3. * Reallocates an array with a new size, and copies the contents
  4. * of the old array to the new array.
  5. * @param oldArray  the old array, to be reallocated.
  6. * @param newSize   the new array size.
  7. * @return          A new array with the same contents.
  8. */
  9. private static Object resizeArray (Object oldArray, int newSize) {   
  10. int ldSize = 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. // 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);   
  27. }
复制代码



回复

使用道具 举报

该用户从未签到

发表于 2011-8-4 21:21:38 | 显示全部楼层
谢谢楼主分享。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

GMT+8, 2024-5-9 07:21 , Processed in 0.438491 second(s), 47 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表