20个JAVA人员非常有用的功能代码

来源:互联网 发布:2017年进出口贸易数据 编辑:程序博客网 时间:2024/05/02 03:01
本文将为大家介绍20人员非常有用的Java功能代码。这20段代码,可以成为大家在今后的开发过程中,Java编程手册的重要部分。

1. 把Strings转换成int和把int转换成String
  1. String a = String.valueOf(2);   //integer to numeric string
  2. int i = Integer.parseInt(a); //numeric string to an int
复制代码
2. 向Java文件中添加文本
  1. Updated: Thanks Simone for pointing to exception. I have 

  2. changed the code.  

  3. BufferedWriter out = null;
  4. try {
  5. out = new BufferedWriter(new FileWriter(”filename”, true));
  6. out.write(”aString”);
  7. } catch (IOException e) {
  8. // error processing code
  9. } finally {
  10. if (out != null) {
  11. out.close();
  12. }
  13. }
复制代码
3. 获取Java现在正调用的方法名 
  1. String methodName = Thread.currentThread().getStackTrace()[1].getMethodName ();
复制代码
4. 在Java中将String型转换成Date型
  1. java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);  
  2. or 
  3. SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );  
  4. Date date = format.parse( myString );
复制代码
5. 通过Java JDBC链接Oracle数据库
  1. public class OracleJdbcTest
  2. {
  3. String driverClass = "oracle.jdbc.driver.OracleDriver";

  4. Connection con;

  5. public void init(FileInputStream fs) throws ClassNotFoundException,

  6. SQLException, FileNotFoundException, IOException
  7. {
  8. Properties props = new Properties();
  9. props.load (fs);
  10. String url = props.getProperty ("db.url");
  11. String userName = props.getProperty ("db.user");
  12. String password = props.getProperty ("db.password");
  13. Class.forName(driverClass);

  14. con=DriverManager.getConnection(url, userName, password);
  15. }

  16. public void fetch() throws SQLException, IOException
  17. {
  18. PreparedStatement ps = con.prepareStatement("select SYSDATE from

  19. dual");
  20. ResultSet rs = ps.executeQuery();

  21. while (rs.next())
  22. {
  23. // do the thing you do
  24. }
  25. rs.close();
  26. ps.close ();
  27. }

  28. public static void main(String[] args)
  29. {
  30. OracleJdbcTest test = new OracleJdbcTest ();
  31. test.init();
  32. test.fetch();
  33. }
  34. }
复制代码
6.将Java中的util.Date转换成sql.Date
这一片段显示如何将一个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快速复制Java文件
  1. public static void fileCopy( File in, File out )
  2. throws IOException
  3. {
  4. FileChannel inChannel = new FileInputStream( in ).getChannel ();
  5. FileChannel outChannel = new FileOutputStream( out ).getChannel();
  6. try
  7. {
  8. //          inChannel.transferTo (0, inChannel.size(), outChannel);      // original

  9. -- apparently has trouble copying large files on Windows

  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. 在Java中创建缩略图
  1. private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)
  2. throws InterruptedException, FileNotFoundException, IOException
  3. {
  4. // load image from filename
  5. Image image = Toolkit.getDefaultToolkit().getImage (filename);
  6. MediaTracker mediaTracker = new MediaTracker(new Container());
  7. mediaTracker.addImage(image, 0);
  8. mediaTracker.waitForID(0);
  9. // use this to test for errors at this point: System.out.println

  10. (mediaTracker.isErrorAny());

  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. // draw original image to thumbnail image object and
  22. // scale it to the new size on-the- fly
  23. BufferedImage thumbImage = new BufferedImage(thumbWidth,

  24. thumbHeight, BufferedImage.TYPE_INT_RGB);
  25. Graphics2D graphics2D = thumbImage.createGraphics();
  26. graphics2D.setRenderingHint (RenderingHints.KEY_INTERPOLATION,

  27. RenderingHints.VALUE_INTERPOLATION_BILINEAR);
  28. graphics2D.drawImag e(image, 0, 0, thumbWidth, thumbHeight, null);

  29. // save thumbnail image to outFilename
  30. BufferedOutputStream out = new BufferedOutputStream(new

  31. FileOutputStream(outFilename));
  32. JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
  33. JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam

  34. (thumbImage);
  35. quality = Math.max(0, Math.min(quality, 100));
  36. param.setQuality((float)quality / 100.0f, false);
  37. encoder.setJPEGEncodeParam (param);
  38. encoder.encode(thumbImage);
  39. out.close ();
  40. }
复制代码
9. 在Java中创建JSON数据
  1. Read this article for more details.
  2. Download JAR file json
  3. -rpc-1.0.jar (75 kb)
  4. import org.json.JSONObject;
  5. ...
  6. ...
  7. JSONObject json = new JSONObject();
  8. json.put("city", "Mumbai");
  9. json.put("country", "India");
  10. ...
  11. String output = json.toString();
  12. ...
复制代码
10. 在Java中使用iText JAR打开PDF
  1. Read this article for more details.

  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.OutputStream;
  5. import java.util.Date;

  6. import com.lowagie.text.Document;
  7. import com.lowagie.text.Paragraph;
  8. import com.lowagie.text.pdf.PdfWriter;

  9. public class GeneratePDF {

  10. public static void main(String[] args) {
  11. try {
  12. OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));

  13. Document document = new Document ();
  14. PdfWriter.getInstance(document, file);
  15. document.open ();
  16. document.add(new Paragraph("Hello Kiran"));
  17. document.add(new Paragraph(new Date().toString()));

  18. document.close ();
  19. file.close();

  20. } catch (Exception e) {

  21. e.printStackTrace();
  22. }
  23. }
  24. }
复制代码
11. 在Java上的HTTP代理设置 
  1. System.getProperties().put("http.proxyHost", "someProxyURL");
  2. System.getProperties().put("http.proxyPort", "someProxyPort");
  3. System.getProperties().put("http.proxyUser", "someUserName");
  4. System.getProperties().put("http.proxyPassword", "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. //Marking default constructor private
  9. //to avoid direct instantiation.
  10. private SimpleSingleton() {
  11. }

  12. //Get instance for class SimpleSingleton
  13. public static SimpleSingleton getInstance() {

  14. return singleInstance;
  15. }
  16. }
  17. One more implementation of Singleton class. Thanks to Ralph and Lukasz Zielinski

  18. for pointing this out.


  19. public enum SimpleSingleton {
  20. INSTANCE;
  21. public void doSomething() {
  22. }
  23. }

  24. //Call the method from Singleton:
  25. SimpleSingleton.INSTANCE.doSomething();
复制代码
13. 在Java上做屏幕截图
  1. Read this article for more details.


  2. import java.awt.Dimension;
  3. import java.awt.Rectangle;
  4. import java.awt.Robot;
  5. import java.awt.Toolkit;
  6. import java.awt.image.BufferedImage;
  7. import javax.imageio.ImageIO;
  8. import java.io.File;

  9. ...

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

  11. Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize ();
  12. Rectangle screenRectangle = new Rectangle (screenSize);
  13. Robot robot = new Robot();
  14. BufferedImage image = robot.createScreenCapture(screenRectangle);
  15. ImageIO.write(image, "png", new File(fileName));

  16. }
  17. ...
复制代码
14. 在Java中的文件,目录列表
  1. File dir = new File("directoryName");
  2. String[] children = dir.list();
  3. if (children == null) {
  4. // Either dir does not exist or is not a directory
  5. } else {
  6. for (int i=0; i < children.length; i++) {
  7. // Get filename of file or directory
  8. String filename = children;
  9. }
  10. }

  11. // It is also possible to filter the list of returned files.
  12. // This example does not return any files that start with `.'.
  13. FilenameFilter filter = new FilenameFilter() {
  14. public boolean accept(File dir, String name) {
  15. return ! name.startsWith(".");
  16. }
  17. };
  18. children = dir.list(filter);

  19. // The list of files can also be retrieved as File objects
  20. File[] files = dir.listFiles();

  21. // This filter only returns directories
  22. FileFilter fileFilter = new FileFilter() {
  23. public boolean accept(File file) {
  24. return file.isDirectory();
  25. }
  26. };
  27. files = dir.listFiles (fileFilter);
复制代码
15. 在Java中创建ZIP和JAR文件
  1. import java.util.zip.*;
  2. import java.io.*;

  3. public class ZipIt {
  4. public static void main(String args []) throws IOException {
  5. if (args.length < 2) {
  6. System.err.println("usage: java ZipIt Zip.zip file1 file2 file3");
  7. System.exit(-1);
  8. }
  9. File zipFile = new File(args [0]);
  10. if (zipFile.exists()) {
  11. System.err.println("Zip file already exists, please try another");
  12. System.exit(-2);
  13. }
  14. FileOutputStream fos = new FileOutputStream(zipFile);
  15. ZipOutputStream zos = new ZipOutputStream (fos);
  16. int bytesRead;
  17. byte[] buffer = new byte [1024];
  18. CRC32 crc = new CRC32 ();
  19. for (int i=1, n=args.length; i < n; i++) {
  20. String name = args;
  21. File file = new File (name);
  22. if (!file.exists()) {
  23.    System.err.println("Skipping: " + name);
  24. & nbsp;   continue;
  25. }
  26. BufferedInputStream bis = new BufferedInputStream (
  27.    new FileInputStream (file));
  28. crc.reset();
  29. while ((bytesRead = bis.read(buffer)) != -1) {
  30.    crc.update(buffer, 0, bytesRead);
  31. }
  32. bis.close ();
  33. // Reset to beginning of input stream
  34. bis = new BufferedInputStream (
  35.    new FileInputStream (file));
  36. ZipEntry entry = new ZipEntry (name);
  37. entry.setMethod (ZipEntry.STORED);
  38. & nbsp; entry.setCompressedSize(file.length ());
  39. entry.setSize(file.length ());
  40. entry.setCrc(crc.getValue ());
  41. zos.putNextEntry (entry);
  42. while ((bytesRead = bis.read(buffer)) != -1) {
  43.    zos.write(buffer, 0, bytesRead);
  44. }
  45. bis.close ();
  46. }
  47. zos.close();
  48. }
  49. }
复制代码
16. Parsing / Reading XML file in Java
  1. Sample XML file.
  2. //...

  3. package net.viralpatel.java.xmlparser;

  4. import java.io.File;
  5. import javax.xml.parsers.DocumentBuilder;
  6. import javax.xml.parsers.DocumentBuilderFactory;

  7. import org.w3c.dom.Document;
  8. import org.w3c.dom.Element;
  9. import org.w3c.dom.Node;
  10. import org.w3c.dom.NodeList;

  11. public class XMLParser {

  12. public void getAllUserNames(String fileName) {
  13. try {
  14. DocumentBuilderFactory dbf =

  15. DocumentBuilderFactory.newInstance();
  16. DocumentBuilder db = dbf.newDocumentBuilder();
  17. File file = new File (fileName);
  18. if (file.exists()) {
  19. Document doc = db.parse (file);
  20. Element docEle = doc.getDocumentElement();

  21. // Print root element of the document
  22. System.out.println("Root element of the document: "
  23. + docEle.getNodeName());

  24. NodeList studentList = docEle.getElementsByTagName

  25. ("student");

  26. // Print total student elements in document
  27. System.out
  28. &nb sp;.println("Total students: " +

  29. studentList.getLength());

  30. if (studentList != null && studentList.getLength()

  31. > 0) {
  32. for (int i = 0; i < studentList.getLength

  33. (); i++) {

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

  35. if (node.getNodeType() ==

  36. Node.ELEMENT_NODE) {

  37. System.out
  38.      .println

  39. ("=====================");

  40. Element e = (Element) node;
  41. NodeList nodeList =

  42. e.getElementsByTagName ("name");
  43. System.out.println("Name: "
  44. +

  45. nodeList.item(0).getChildNodes().item(0)

  46. .getNodeValue());

  47. nodeList =

  48. e.getElementsByTagName ("grade");
  49. System.out.println("Grade:

  50. "
  51. +

  52. nodeList.item(0).getChildNodes().item(0)

  53. .getNodeValue());

  54. nodeList =

  55. e.getElementsByTagName ("age");
  56. System.out.println("Age: "
  57. +

  58. nodeList.item(0).getChildNodes().item(0)

  59. .getNodeValue());
  60. }
  61. }
  62. } else {
  63. System.exit(1);
  64. }
  65. }
  66. } catch (Exception e) {
  67. System.out.println(e);
  68. }
  69. }
  70. public static void main(String[] args) {

  71. XMLParser parser = new XMLParser ();
  72. parser.getAllUserNames("c:\\test.xml");
  73. }
  74. }
复制代码
17. Convert Array to Map in Java
  1. import java.util.Map;
  2. import org.apache.commons.lang.ArrayUtils;

  3. public class Main {

  4. public static void main(String[] args) {
  5. String[][] countries = { { "United States", "New York" }, { "United Kingdom",

  6. "London" },
  7. { "Netherland", "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" }

  8. };

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

  10. System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));
  11. System.out.println("Capital of France is " + countryCapitals.get("France"));
  12. }
  13. }
复制代码
18. Send Email using Java

  1. import javax.mail.*;
  2. import javax.mail.internet.*;
  3. import java.util.*;

  4. public void postMail( String recipients[ ], String subject, String message , String

  5. 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. }
复制代码
19. Send HTTP request & fetching data using Java
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.net.URL;

  4. public class Main {
  5. public static void main(String[] args)  {
  6. try {
  7. URL my_url = new URL("http://www.viralpatel.net/blogs/");
  8.    BufferedReader br = new BufferedReader(new

  9. 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. }
复制代码
20. Resize an Array in Java
  1. /**
  2. * Reallocates an array with a new size, and copies the contents
  3. * of the old array to the new array.
  4. * @param oldArray  the old array, to be reallocated.
  5. * @param newSize   the new array size.
  6. * @return          A new array with the same contents.
  7. */
  8. private static Object resizeArray (Object oldArray, int newSize) {  
  9. int oldSize = java.lang.reflect.Array.getLength(oldArray);  
  10. Class elementType = oldArray.getClass().getComponentType();  
  11. Object newArray = java.lang.reflect.Array.newInstance(  
  12. elementType,newSize);  
  13. int preserveLength = Math.min (oldSize,newSize);  
  14. if (preserveLength > 0)   
  15. System.arraycopy (oldArray,0,newArray,0,preserveLength);  
  16. return newArray;  
  17. }  

  18. // Test routine for resizeArray().  
  19. public static void main (String[] args) {  
  20. int[] a = {1,2,3};  
  21. a = (int[])resizeArray(a,5);  
  22. a[3] = 4;  
  23. a[4] = 5;  
  24. for (int i=0; i
  25.       System.out.println (a);  

复制代码
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. }
复制代码
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. }
复制代码
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. }
复制代码
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. }
复制代码
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 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. // 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);   

  1. 原文地址: http://club.topsage.com/thread-2574000-1-2.html

0 0