本文将为大家介绍20个对开发人员非常有用的Java功能代码。这20段代码,可以成为大家在今后的开发过程中,Java编程手册的重要部分。

1. 把Strings转换成int和把int转换成String

  1. <pre class="java" name="code">
  2. String a = String.valueOf(2);
  3. //integer to numeric string
  4. int i = Integer.parseInt(a);
  5. //numeric string to an int
  6. String a = String.valueOf(2);
  7. //integer to numeric string
  8. int i = Integer.parseInt(a);
  9. //numeric string to an int</pre></pre>

2. 向Java文件中添加文本

  1. Updated: Thanks Simone for pointing to exception. I have changed the code.
  2. BufferedWriter out = null;
  3. try {
  4. out = new BufferedWriter(new FileWriter(”filename”, true));
  5. out.write(”aString”);
  6. } catch (IOException e) {
  7. // error processing code
  8. } finally {
  9. if (out != null) {
  10. out.close();
  11. }
  12. }
  13. BufferedWriter out = 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. }

3. 获取Java现在正调用的方法名

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

4. 在Java中将String型转换成Date型

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

    OR

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

5. 通过JavaJDBC链接Oracle数据库

  1. public class OracleJdbcTest {
  2. String driverClass = "oracle.jdbc.driver.OracleDriver";
  3. Connection con;
  4. public void init (FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException {
  5. Properties props = new Properties();
  6. props.load(fs);
  7. String url = props.getProperty("db.url");
  8. String userName = props.getProperty("db.user");
  9. String password = props.getProperty("db.password");
  10. Class.forName(driverClass);
  11. con=DriverManager.getConnection(url, userName, password);
  12. }
  13. public void fetch() throws SQLException, IOException {
  14. PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");
  15. ResultSet rs = ps.executeQuery();
  16. while (rs.next()) {
  17. // do the thing you do
  18. }
  19. rs.close();
  20. ps.close();
  21. }
  22. public static void main(String[] args) {
  23. OracleJdbcTest test = new OracleJdbcTest();
  24. test.init();
  25. test.fetch();
  26. }
  27. }
  28. public class OracleJdbcTest {
  29. String driverClass = "oracle.jdbc.driver.OracleDriver";
  30. Connection con;
  31. public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException {
  32. Properties props = new Properties();
  33. props.load(fs);
  34. String url = props.getProperty("db.url");
  35. String userName = props.getProperty("db.user");
  36. String password = props.getProperty("db.password");
  37. Class.forName(driverClass);
  38. con=DriverManager.getConnection(url, userName, password);
  39. }
  40. public void fetch() throws SQLException, IOException {
  41. PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");
  42. ResultSet rs = ps.executeQuery();
  43. while (rs.next()) {
  44. // do the thing you do
  45. }
  46. rs.close();
  47. ps.close();
  48. }
  49. public static void main(String[] args) {
  50. OracleJdbcTest test = new OracleJdbcTest();
  51. test.init();
  52. test.fetch();
  53. }
  54. }

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 ) throws IOException {
  2. FileChannel inChannel = new FileInputStream( in ).getChannel();
  3. FileChannel outChannel = new FileOutputStream( out ).getChannel();
  4. try {
  5. // original -- apparently has trouble copying large files on Windows
  6. // magic number for Windows, 64Mb - 32Kb)
  7. inChannel.transferTo(0, inChannel.size(), outChannel);
  8. int maxCount = (64 * 1024 * 1024) - (32 * 1024);long size = inChannel.size();
  9. long position = 0;
  10. while (position < size ) {
  11. position += inChannel.transferTo( position, maxCount, outChannel );
  12. }
  13. } finally {
  14. if (inChannel != null) {
  15. inChannel.close();
  16. }
  17. if (outChannel != null) {
  18. outChannel.close();
  19. }
  20. }
  21. }

8. 在Java中创建缩略图

  1. private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)
  2. throws InterruptedException, FileNotFoundException, IOException {
  3. // load image from filename
  4. Image image = Toolkit.getDefaultToolkit().getImage(filename);
  5. MediaTracker mediaTracker = new
  6. MediaTracker(new Container());
  7. mediaTracker.addImage(image, 0);
  8. mediaTracker.waitForID(0);
  9. // use this to test for errors at this point:
  10. System.out.println(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 scale it to the new size on-the-fly
  22. BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
  23. Graphics2D graphics2D = thumbImage.createGraphics();
  24. graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
  25. graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
  26. // save thumbnail image to
  27. outFilename BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));
  28. JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
  29. JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
  30. quality = Math.max(0, Math.min(quality, 100));
  31. param.setQuality((float)quality / 100.0f, false);
  32. encoder.setJPEGEncodeParam(param);
  33. encoder.encode(thumbImage);
  34. out.close();
  35. }

9. 在Java中创建JSON数据

  1. Read this article for more details. Download JAR file json-rpc-1.0.jar (75 kb)
  2. import org.json.JSONObject;
  3. ...
  4. ...
  5. JSONObject json = new JSONObject();
  6. json.put("city", "Mumbai");
  7. json.put("country", "India");
  8. ...
  9. String output = json.toString();
  10. ...

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 details.
  2. Update: Thanks Markus for the comment. I have updated the code and changed it to more robust implementation.
  3. public class SimpleSingleton {
  4. private static SimpleSingleton singleInstance =  new SimpleSingleton();
  5. //Marking default constructor private
  6. //to avoid direct instantiation.
  7. private SimpleSingleton() {
  8. }
  9. //Get instance for class SimpleSingleton
  10. public static SimpleSingleton getInstance() {
  11. return singleInstance;
  12. }
  13. }
  14. One more implementation of Singleton class. Thanks to Ralph and Lukasz Zielinski for pointing this out.
  15. public enum SimpleSingleton {
  16. INSTANCE;
  17. public void doSomething() {
  18. }
  19. }
  20. //Call the method from Singleton:
  21. SimpleSingleton.INSTANCE.doSomething();
  22. public enum SimpleSingleton {
  23. INSTANCE;
  24. public void doSomething() {
  25. }
  26. }

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[i];
  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[i];
  21. File file = new File(name);
  22. if (!file.exists()) {
  23. System.err.println("Skipping: " + name);
  24. continue;
  25. }
  26. BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
  27. crc.reset();
  28. while ((bytesRead = bis.read(buffer)) != -1) {
  29. crc.update(buffer, 0, bytesRead);
  30. }
  31. bis.close();
  32. // Reset to beginning of input stream
  33. bis = new BufferedInputStream(new FileInputStream(file));
  34. ZipEntry entry = new ZipEntry(name);
  35. entry.setMethod(ZipEntry.STORED);
  36. entry.setCompressedSize(file.length());
  37. entry.setSize(file.length());
  38. entry.setCrc(crc.getValue());
  39. zos.putNextEntry(entry);
  40. while ((bytesRead = bis.read(buffer)) != -1) {
  41. zos.write(buffer, 0, bytesRead);
  42. }
  43. bis.close();
  44. }
  45. zos.close();
  46. }
  47. }

16. 在Java中解析/读取XML文件

  1. <?xml version="1.0"?>
  2. <students>
  3. <student>
  4. <name>John</name>
  5. <grade>B</grade>
  6. <age>12</age>
  7. </student>
  8. <student>
  9. <name>Mary</name>
  10. <grade>A</grade>
  11. <age>11</age>
  12. </student>
  13. <student>
  14. <name>Simon</name>
  15. <grade>A</grade>
  16. <age>18</age>
  17. </student>
  18. </students>

Java code to parse above XML.

  1. package net.viralpatel.java.xmlparser;
  2. import java.io.File;
  3. import javax.xml.parsers.DocumentBuilder;
  4. import javax.xml.parsers.DocumentBuilderFactory;
  5. import org.w3c.dom.Document;
  6. import org.w3c.dom.Element;
  7. import org.w3c.dom.Node;
  8. import org.w3c.dom.NodeList;
  9. public class XMLParser {
  10. public void getAllUserNames(String fileName) {
  11. try {
  12. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  13. DocumentBuilder db = dbf.newDocumentBuilder();
  14. File file = new File(fileName);
  15. if (file.exists()) {
  16. Document doc = db.parse(file);
  17. Element docEle = doc.getDocumentElement();
  18. // Print root element of the document
  19. System.out.println("Root element of the document: " + docEle.getNodeName());
  20. NodeList studentList = docEle.getElementsByTagName("student");
  21. // Print total student elements in document
  22. System.out.println("Total students: " + studentList.getLength());
  23. if (studentList != null && studentList.getLength() > 0) {
  24. for (int i = 0; i < studentList.getLength(); i++) {
  25. Node node = studentList.item(i);
  26. if (node.getNodeType() == Node.ELEMENT_NODE) {
  27. System.out.println("=====================");
  28. Element e = (Element) node;
  29. NodeList nodeList = e.getElementsByTagName("name");
  30. System.out.println("Name: "
  31. + nodeList.item(0).getChildNodes().item(0).getNodeValue());
  32. nodeList = e.getElementsByTagName("grade");
  33. System.out.println("Grade: " + nodeList.item(0).getChildNodes().item(0).getNodeValue());
  34. nodeList = e.getElementsByTagName("age");
  35. System.out.println("Age: " + nodeList.item(0).getChildNodes().item(0)
  36. .getNodeValue());
  37. }
  38. }
  39. } else {
  40. System.exit(1);
  41. }
  42. }
  43. } catch (Exception e) {
  44. ystem.out.println(e);
  45. }
  46. }
  47. public static void main(String[] args) {
  48. XMLParser parser = new XMLParser();
  49. parser.getAllUserNames("c:\\test.xml");
  50. }
  51. }

17. 在Java中将Array转换成Map

  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 = {
  6. { "United States", "New York" },
  7. { "United Kingdom", "London" },
  8. { "Netherland", "Amsterdam" },
  9. { "Japan", "Tokyo" },
  10. { "France", "Paris" }
  11. };
  12. Map countryCapitals = ArrayUtils.toMap(countries);
  13. System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));
  14. System.out.println("Capital of France is " + countryCapitals.get("France"));
  15. }
  16. }

18. 在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 from) throws MessagingException {
  5. boolean debug = false;
  6. //Set the host smtp address
  7. Properties props = new Properties();
  8. props.put("mail.smtp.host", "smtp.example.com");
  9. // create some properties and get the default Session
  10. Session session = Session.getDefaultInstance(props, null);
  11. session.setDebug(debug);
  12. // create a message
  13. Message msg = new MimeMessage(session);
  14. // set the from and to address
  15. InternetAddress addressFrom = new InternetAddress(from);
  16. msg.setFrom(addressFrom);
  17. InternetAddress[] addressTo = new InternetAddress[recipients.length];
  18. for (int i = 0; i < recipients.length; i++) {
  19. addressTo[i] = new InternetAddress(recipients[i]);
  20. }
  21. msg.setRecipients(Message.RecipientType.TO, addressTo);
  22. // Optional : You can also set your custom headers in the Email if you Want
  23. msg.addHeader("MyHeaderName", "myHeaderValue");
  24. // Setting the Subject and Content Type
  25. msg.setSubject(subject);
  26. msg.setContent(message, "text/plain");
  27. Transport.send(msg);
  28. }

19. 使用Java发送HTTP请求和提取数据

  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 InputStreamReader(my_url.openStream()));
  9. String strTemp = "";
  10. while(null != (strTemp = br.readLine())) {
  11. System.out.println(strTemp);
  12. }
  13. } catch (Exception ex) {
  14. ex.printStackTrace();
  15. }
  16. }
  17. }

20. 在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(elementType,newSize);
  12. int preserveLength = Math.min(oldSize,newSize);
  13. if (preserveLength > 0)
  14. System.arraycopy (oldArray,0,newArray,0,preserveLength);
  15. return newArray;
  16. }
  17. // Test routine for resizeArray().
  18. public static void main (String[] args) {
  19. int[] a = {1,2,3};
  20. a = (int[])resizeArray(a,5);
  21. a[3] = 4;
  22. a[4] = 5;
  23. for (int i=0; i<a.length; i++)
  24. System.out.println (a[i]);
  25. }

20个开发人员非常有用的Java功能代码的更多相关文章

  1. IOS开发-OC学习-常用功能代码片段整理

    IOS开发-OC学习-常用功能代码片段整理 IOS开发中会频繁用到一些代码段,用来实现一些固定的功能.比如在文本框中输入完后要让键盘收回,这个需要用一个简单的让文本框失去第一响应者的身份来完成.或者是 ...

  2. Spring Boot 针对 Java 开发人员的安装指南

    Spring Boot 可以使用经典的开发工具或者使用安装的命令行工具.不管使用何种方式,你都需要确定你的 Java 版本为 Java SDK v1.8 或者更高的版本.在你开始安装之前,你需要确定你 ...

  3. 每个Java开发人员都应该知道的10个基本工具

    大家好,我们已经在2019年的第9个月,我相信你们所有人已经在2019年学到了什么,以及如何实现这些目标.我一直在写一系列文章,为你提供一些关于你可以学习和改进的想法,以便在2019年成为一个更好的. ...

  4. Java开发人员必备十大工具

    Java世界中存在着很多工具,从著名的IDE(例如Eclipse,NetBeans和IntelliJ IDEA)到JVM profiling和监视工具(例如JConsole,VisualVM,Ecli ...

  5. C#开发人员应该知道的13件事情

    本文讲述了C#开发人员应该了解到的13件事情,希望对C#开发人员有所帮助. 1. 开发过程 开发过程是错误和缺陷开始的地方.使用工具可以帮助你在发布之后,解决掉一些问题. 编码标准 遵照编码标准可以编 ...

  6. 【Tomcat】面向初级 Web 开发人员的 Tomcat

    Apache Tomcat 应用服务器不再是高级 Web 系统开发人员的专用领域.在本教程中,Sing Li 将向初级 Web 开发人员展示如何利用他们当前的 Java™ 开发技能,使用 Tomcat ...

  7. 初级 Web 开发人员的 Tomcat

    介绍使用 Tomcat 对 JavaServer Pages (JSP).servlet 和 Web 服务进行编程,Tomcat 是来自 Apache Foundation 的开源应用服务器.本教程引 ...

  8. .NET开发人员值得关注的七个开源项目 .

    NET开发人员值得关注的七个开源项目 软近几年在.NET社区开源项目方面投入了相当多的时间和资源,不禁让原本对峙的开源社区阵营大吃一惊,从微软.NET社区中的反应来看,微软.NET开发阵营对开源工具的 ...

  9. 开发人员如何从官网首页进入下载JDK历史版本

    就是下面的这篇文章,好心好意提交到百度经验,希望给需要的人一个帮助,结果被拒,说有广告.呵呵,oracle和java真的需要在你百度上面做广告吗?倒是能理解,可能是外行人做的,只是看到链接就拒了,但是 ...

随机推荐

  1. 关于EF 通用增删改查的封装

    1.  Entity Framework是Microsoft的ORM框架,随着 Entity Framework 不断的完善强化已经到达了EF 6.0+ 还是非常的完善的,目前使用的比例相对于其他OR ...

  2. 业余草教你解读Spark源码阅读之HistoryServer

    HistoryServer服务可以让用户通过Spark UI界面,查看历史应用(已经执行完的应用)的执行细节,比如job信息.stage信息.task信息等,该功能是基于spark eventlogs ...

  3. 解决React Native unable to load script from assets index.android.bundle on windows

    React Native运行的时候,经常碰到React Native unable to load script from assets index.android.bundle on windows ...

  4. (转)XML中必须进行转义的字符

    场景:在工作中接触到很多xml文件,为了更好的操作这些文件,所有很有必要熟知xml文件的相关语义. 1 引入 编写XML代码经常遗漏的常识: XML实体中不允许出现"&", ...

  5. HDOJ2002-计算球体面积

    Problem Description 根据输入的半径值,计算球的体积.   Input 输入数据有多组,每组占一行,每行包括一个实数,表示球的半径.   Output 输出对应的球的体积,对于每组输 ...

  6. Python学习记录----IDE安装

    摘要: 安装eric5 一 确定python版本 安装的最新版本:python3.3 下载连接:http://www.python.org/getit/ 二 确定pyqt版本 安装的最新版本:PyQt ...

  7. 简单聊聊不可或缺的Nginx反向代理服务器--实现负载均衡【上篇】

    今天又是新的一周,我养足了精神去对待新一周的工作,但是今天到公司发现还是有一点空闲时间的,所以就想与之前接触过的Nginx再交往得更深一点儿. 什么是Nginx: Nginx是一款高性能的http服务 ...

  8. webpack开发与生产环境配置

    前言 作者去年就开始使用webpack, 最早的接触就来自于vue-cli.那个时候工作重点主要也是 vue 的使用,对webpack的配置是知之甚少,期间有问题也是询问大牛 @吕大豹.顺便说一句,对 ...

  9. POJ 2386 Lake Counting (简单深搜)

    Description Due to recent rains, water has pooled in various places in Farmer John's field, which is ...

  10. ubuntu下统计目录及其子目录文件个数

    查看某目录下文件的个数 ls -l |grep "^-"|wc -l 或 find ./company -type f | wc -l 查看某目录下文件的个数,包括子目录里的. l ...