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入门到精通教程
查看: 897|回复: 0

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

[复制链接]

该用户从未签到

发表于 2011-7-26 22:38:09 | 显示全部楼层 |阅读模式
1. 把Strings转换成int和把int转换成String
  1. String a = String.valueOf(2);
  2.             //integer to numeric string   
  3.             int i = Integer.parseInt(a); //numeric
  4.             string to an int
  5.             
  6.             String a = String.valueOf(2);   
  7.             //integer to numeric string
  8.             int i = Integer.parseInt(a); //numeric string to an int
复制代码

2. 向java文件中添加文本
  1. java.util.Date =
  2.             java.text.DateFormat.getDateInstance().parse(date String);
  3.             
  4.             java.util.Date = java.text.DateFormat.getDateInstance().parse(date
  5.             String);or
  6.             SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy"
  7.             );   
  8.             Date date = format.parse( myString );
  9.             SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );
  10.             Date date
  11.             = format.parse( myString );
  12. Updated: Thanks Simone for pointing to exception. I havechanged the code.
  13. BufferedWriter ut = null;   
  14. try{   
  15. out = new BufferedWriter(new FileWriter(”filename”, true));   
  16. out.write(”aString”);   
  17. } catch (IOException e) {   
  18. // error processing code   
  19. } finally{   
  20. if (out != null) {   
  21. out.close();   
  22. }   
  23. }   
  24. BufferedWriter ut = null;
  25. try {
  26. out = new BufferedWriter(newFileWriter(”filename”, true));
  27. out.write(”aString”);
  28. } catch(IOException e) {
  29. // error processing code
  30. } finally {
  31. if (out!= null) {
  32. out.close();
  33. }
  34. }
复制代码

3. 获取java现在正调用的方法名
  1. String methodName =
  2.             Thread.currentThread().getStackTrace()[1].getMethodName();
  3.             String methodName = Thread.currentThread().getStackTrace()[1].getMethodName
  4.             ();
复制代码

4. 在java中将String型转换成Date型
  1. java.util.Date =
  2.             java.text.DateFormat.getDateInstance().parse(date String);
  3.             
  4.             java.util.Date = java.text.DateFormat.getDateInstance().parse(date
  5.             String);or
  6.             SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy"
  7.             );   
  8.             Date date = format.parse( myString );
  9.             SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );
  10.             Date date
  11.             = format.parse( myString );
复制代码

5. 通过java jdbc链接oracle数据库
  1. public class oraclejdbcTest   
  2. {   
  3. String driverClass =
  4. "oracle.jdbc.driver.oracleDriver";   
  5. Connection con;   
  6. public void init
  7. (FileInputStream fs) throws ClassNotFoundException,
  8. SQLException, FileNotFoundException, IOException   
  9. {   
  10. Properties props = new Properties();   
  11. props.load(fs);   
  12. String url = props.getProperty
  13. ("db.url");   
  14. String
  15. userName = props.getProperty("db.user");   
  16. String password = props.getProperty
  17. ("db.password");   
  18. Class.forName(driverClass);   
  19. con=DriverManager.getConnection(url,
  20. userName, password);   
  21. }   
  22. public void fetch() throws SQLException,
  23. IOException   
  24. {   
  25. PreparedStatement ps =
  26. con.prepareStatement("select SYSDATE from dual");   
  27. ResultSet rs = ps.executeQuery
  28. ();   
  29. while
  30. (rs.next())   
  31. {   
  32. // do the
  33. thing you do   
  34. }
  35.    
  36. rs.close();   
  37. ps.close();   
  38. }   
  39. public
  40. static void main(String[] args)   
  41. {   
  42. oraclejdbcTest test = new
  43. oraclejdbcTest();   
  44. test.init();   
  45. test.fetch
  46. ();   
  47. }   
  48. }
  49. public class oraclejdbcTest
  50. {
  51. String driverClass =
  52. "oracle.jdbc.driver.oracleDriver";
  53. Connection con;
  54. public void init(FileInputStream fs) throws ClassNotFoundException,
  55. SQLException, FileNotFoundException, IOException
  56. {
  57. Properties props = new Properties();
  58. props.load
  59. (fs);
  60. String url = props.getProperty
  61. ("db.url");
  62. String userName = props.getProperty
  63. ("db.user");
  64. String password = props.getProperty
  65. ("db.password");
  66. Class.forName(driverClass);
  67. con=DriverManager.getConnection(url, userName,
  68. password);
  69. }
  70. public void fetch() throws SQLException, IOException
  71. {
  72. PreparedStatement ps = con.prepareStatement("select SYSDATE from
  73. dual");
  74. ResultSet rs = ps.executeQuery();
  75. while (rs.next())
  76. {
  77. // do the
  78. thing you do
  79. }
  80. rs.close();
  81. ps.close
  82. ();
  83. }
  84. public static void main(String[] args)
  85. {
  86. oraclejdbcTest test = new oraclejdbcTest
  87. ();
  88. test.init();
  89. test.fetch();
  90. }
  91. }
复制代码

6.将java中的util.Date转换成sql.Date
这一片段显示如何将一个java util Date转换成sql Date用于数据库
  1. java.util.Date utilDate = new
  2.             java.util.Date();   
  3.             java.sql.Date sqlDate = new java.sql.Date
  4.             (utilDate.getTime());
  5.             
  6.             java.util.Date utilDate = new java.util.Date();
  7.             java.sql.Date sqlDate =
  8.             new java.sql.Date(utilDate.getTime());
复制代码

7. 使用NIO快速复制java文件
  1. public static void fileCopy( File in, File out )
  2.    
  3. throws IOException   
  4. {   
  5. FileChannel inChannel = new
  6. FileInputStream( in ).getChannel();   
  7. FileChannel utChannel = new
  8. FileOutputStream( out ).getChannel();   
  9. try
  10. {   
  11. //          inChannel.transferTo
  12. (0, inChannel.size(), outChannel);      // original
  13. -- apparently has trouble copying large files on Windows   
  14. // magic
  15. number for Windows, 64Mb - 32Kb)   
  16. int maxCount
  17. = (64 * 1024 * 1024) - (32 * 1024);   
  18. long size =
  19. inChannel.size();   
  20. long
  21. position = 0;   
  22. while (
  23. position < size )   
  24. {   
  25. &
  26. nbsp; position += inChannel.transferTo( position, maxCount, outChannel );
  27. }
  28.    
  29. }   
  30. finally
  31. {   
  32. if (
  33. inChannel != null )   
  34. {   
  35. &
  36. nbsp; inChannel.close();   
  37. }
  38.    
  39. if ( outChannel != null )   
  40. {   
  41. &
  42. nbsp;  outChannel.close();   
  43. }
  44.    
  45. }   
  46. }
  47. public static void fileCopy( File in, File out )
  48. throws
  49. IOException
  50. {
  51. FileChannel inChannel = new FileInputStream( in ).getChannel
  52. ();
  53. FileChannel utChannel = new
  54. FileOutputStream( out ).getChannel();
  55. try
  56. {
  57. //          inChannel.transferTo
  58. (0, inChannel.size(), outChannel);      // original
  59. -- apparently has trouble copying large files on Windows
  60. // magic
  61. number for Windows, 64Mb - 32Kb)
  62. int maxCount
  63. = (64 * 1024 * 1024) - (32 *
  64. 1024);
  65. long
  66. size = inChannel.size
  67. ();
  68. long
  69. position = 0;
  70. while ( position < size )
  71. {
  72.   position += inChannel.transferTo( position, maxCount, outChannel
  73. );
  74. }
  75. }
  76. finally
  77. {
  78. if (
  79. inChannel != null )
  80. {
  81.   inChannel.close
  82. ();
  83. }
  84. if (
  85. outChannel != null )
  86. {
  87.    outChannel.close
  88. ();
  89. }
  90. }
  91. }
复制代码

8. 在java中创建缩略图
  1. private void createThumbnail(String filename, int thumbWidth,
  2. int thumbHeight, int
  3. quality, String outFilename)   
  4. throws InterruptedException,
  5. FileNotFoundException, IOException   
  6. {   
  7. // load image from
  8. filename   
  9. Image image =
  10. Toolkit.getDefaultToolkit().getImage(filename);   
  11. MediaTracker mediaTracker = new
  12. MediaTracker(new Container());   
  13. mediaTracker.addImage(image,
  14. 0);   
  15. mediaTracker.waitForID(0);   
  16. // use this to test for errors at
  17. this point: System.out.println
  18. (mediaTracker.isErrorAny());   
  19. // determine thumbnail size from
  20. WIDTH and HEIGHT   
  21. double
  22. thumbRatio = (double)thumbWidth / (double)thumbHeight;   
  23. int imageWidth = image.getWidth
  24. (null);   
  25. int imageHeight
  26. = image.getHeight(null);   
  27. double imageRatio = (double)imageWidth / (double)imageHeight;   
  28. if (thumbRatio < imageRatio)
  29. {   
  30. thumbHeight
  31. = (int)(thumbWidth / imageRatio);   
  32. } else {   
  33. thumbWidth =
  34. (int)(thumbHeight * imageRatio);   
  35. }   
  36. // draw original image to thumbnail
  37. image object and   
  38. //
  39. scale it to the new size on-the-fly   
  40. BufferedImage thumbImage = new
  41. BufferedImage(thumbWidth, thumbHeight,
  42. BufferedImage.TYPE_INT_RGB);   
  43. Graphics2D graphics2D =
  44. thumbImage.createGraphics();   
  45. graphics2D.setRenderingHint
  46. (RenderingHints.KEY_INTERPOLATION,
  47. RenderingHints.VALUE_INTERPOLATION_BILINEAR);   
  48. graphics2D.drawImage(image, 0, 0,
  49. thumbWidth, thumbHeight, null);   
  50. // save thumbnail image to
  51. outFilename   
  52. BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream
  53. (outFilename));   
  54. JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);   
  55. JPEGEncodeParam param =
  56. encoder.getDefaultJPEGEncodeParam(thumbImage);   
  57. quality = Math.max(0, Math.min
  58. (quality, 100));   
  59. param.setQuality((float)quality / 100.0f, false);   
  60. encoder.setJPEGEncodeParam
  61. (param);   
  62. encoder.encode
  63. (thumbImage);   
  64. out.close
  65. ();   
  66. }
  67. private void createThumbnail(String filename, int thumbWidth, int
  68. thumbHeight, int
  69. quality, String outFilename)
  70. throws InterruptedException,
  71. FileNotFoundException, IOException
  72. {
  73. // load image from
  74. filename
  75. Image image = Toolkit.getDefaultToolkit().getImage
  76. (filename);
  77. MediaTracker mediaTracker = new MediaTracker(new
  78. Container());
  79. mediaTracker.addImage(image,
  80. 0);
  81. mediaTracker.waitForID(0);
  82. // use this to test
  83. for errors at this point: System.out.println
  84. (mediaTracker.isErrorAny());
  85. // determine thumbnail size from WIDTH and
  86. HEIGHT
  87. double thumbRatio = (double)thumbWidth / (double)
  88. thumbHeight;
  89. int imageWidth = image.getWidth
  90. (null);
  91. int imageHeight = image.getHeight
  92. (null);
  93. double imageRatio = (double)imageWidth / (double)
  94. imageHeight;
  95. if (thumbRatio < imageRatio)
  96. {
  97. thumbHeight = (int)(thumbWidth /
  98. imageRatio);
  99. } else {
  100. thumbWidth = (int)
  101. (thumbHeight * imageRatio);
  102. }
  103. // draw original image to thumbnail image object
  104. and
  105. // scale it to the new size on-the-
  106. fly
  107. BufferedImage thumbImage = new BufferedImage(thumbWidth,
  108. thumbHeight, BufferedImage.TYPE_INT_RGB);
  109. Graphics2D graphics2D =
  110. thumbImage.createGraphics();
  111. graphics2D.setRenderingHint
  112. (RenderingHints.KEY_INTERPOLATION,
  113. RenderingHints.VALUE_INTERPOLATION_BILINEAR);
  114. graphics2D.drawImag
  115. e(image, 0, 0, thumbWidth, thumbHeight, null);
  116. // save thumbnail image to
  117. outFilename
  118. BufferedOutputStream ut = new BufferedOutputStream(new
  119. FileOutputStream(outFilename));
  120. JPEGImageEncoder encoder =
  121. JPEGCodec.createJPEGEncoder(out);
  122. JPEGEncodeParam param =
  123. encoder.getDefaultJPEGEncodeParam
  124. (thumbImage);
  125. quality = Math.max(0, Math.min(quality,
  126. 100));
  127. param.setQuality((float)quality / 100.0f,
  128. false);
  129. encoder.setJPEGEncodeParam
  130. (param);
  131. encoder.encode(thumbImage);
  132. out.close
  133. ();
  134. }
复制代码

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",
  10. "India");   
  11. ...   
  12. String utput = json.toString
  13. ();   
  14. ...
  15. import org.json.JSONObject;
  16. ...
  17. ...
  18. JSONObject json = new
  19. JSONObject();
  20. json.put("city", "Mumbai");
  21. json.put("country",
  22. "India");
  23. ...
  24. String utput = json.toString();
  25. ...
复制代码

10. 在java中使用iText JAR打开PDF
  1. Read this article for more details.
  2. import java.io.File;   
  3. import
  4. java.io.FileOutputStream;   
  5. import java.io.OutputStream;   
  6. import java.util.Date;   
  7. import
  8. com.lowagie.text.Document;   
  9. import
  10. com.lowagie.text.Paragraph;   
  11. import
  12. com.lowagie.text.pdf.PdfWriter;   
  13. public class GeneratePDF
  14. {   
  15. public static void main(String[]
  16. args) {   
  17. try
  18. {   
  19. OutputStream
  20. file = new FileOutputStream(new File("C:\\Test.pdf"));   
  21. Document
  22. document = new Document();   
  23. PdfWriter.getInstance(document, file);   
  24. document.open();   
  25. document.add(new Paragraph("Hello Kiran"));   
  26. document.add(new Paragraph(new Date().toString()));   
  27. document.close();   
  28. file.close
  29. ();   
  30. } catch
  31. (Exception e) {   
  32. e.printStackTrace();   
  33. }
  34.    
  35. }   
  36. }
  37. import java.io.File;
  38. import java.io.FileOutputStream;
  39. import
  40. java.io.OutputStream;
  41. import java.util.Date;
  42. import com.lowagie.text.Document;
  43. import
  44. com.lowagie.text.Paragraph;
  45. import com.lowagie.text.pdf.PdfWriter;
  46. public class GeneratePDF {
  47. public static void main(String[] args)
  48. {
  49. try
  50. {
  51. OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
  52. Document
  53. document = new Document
  54. ();
  55. PdfWriter.getInstance(document,
  56. file);
  57. document.open
  58. ();
  59. document.add(new Paragraph("Hello
  60. Kiran"));
  61. document.add(new Paragraph(new Date().toString()));
  62. document.close
  63. ();
  64. file.close();
  65. } catch (Exception e) {
  66. e.printStackTrace();
  67. }
  68. }
  69. }
复制代码
回复

使用道具 举报

该用户从未签到

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

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-5-8 14:07 , Processed in 0.387788 second(s), 49 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

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