当前位置: 首页 > 编程文章 >

Java常用开发技巧与代码片段汇总

Java常用开发技巧与代码片段汇总

作者:许川时间:2026-02-25 14:02:17浏览:676

本文整理了Java开发中常用的20个代码示例,涵盖基础数据类型转换、文件读写、日期处理、数据库连接及第三方库使用。内容包括String与整型的互转、向文件追加内容、获取当前方法名、字符串解析为Date对象、JDBC连接Oracle、util.Date与sql.Date转换、NIO快速文件拷贝、图片缩略图生成、JSON数据创建、PDF生成、HTTP代理设置、单例模式实现、屏幕抓取、目录列出、ZIP/JAR创建、XML解析、数组转Map、邮件发送、带参数HTTP请求以及动态调整数组大小。这些片段可直接嵌入项目以提升开发效率。

本文目录展开

Java常用开发技巧与代码片段汇总

1. 字符串与整型数据的相互转换

String a = String.valueOf(2); // integer to numeric string int i = Integer.parseInt(a); // numeric string to an int

2. 向文件末尾追加内容


BufferedWriter out = null; 
try { 
  out = new BufferedWriter(new FileWriter(”filename”, true)); 
  out.write(”aString”); 
} catch (IOException e) { 
  // error processing code 
} finally { 
  if (out != null) { 
    out.close(); 
  } 
}

3. 获取当前执行方法的名字

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

4. 将字符串转换为日期对象

java.util.Date = java.text.DateFormat.getDateInstance().parse(date String); 或者是: SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" ); Date date = format.parse( myString );

5. 通过JDBC连接Oracle数据库


public class OracleJdbcTest 
{ 
  String driverClass = "oracle.jdbc.driver.OracleDriver"; 
  
  Connection con; 
  
  public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException 
  { 
    Properties props = new Properties(); 
    props.load(fs); 
    String url = props.getProperty("db.url"); 
    String userName = props.getProperty("db.user"); 
    String password = props.getProperty("db.password"); 
    Class.forName(driverClass); 
  
    con=DriverManager.getConnection(url, userName, password); 
  } 
  
  public void fetch() throws SQLException, IOException 
  { 
    PreparedStatement ps = con.prepareStatement("select SYSDATE from dual"); 
    ResultSet rs = ps.executeQuery(); 
  
    while (rs.next()) 
    { 
      // do the thing you do 
    } 
    rs.close(); 
    ps.close(); 
  } 
  
  public static void main(String[] args) 
  { 
    OracleJdbcTest test = new OracleJdbcTest(); 
    test.init(); 
    test.fetch(); 
  } 
}

6. 将Java util.Date转换为sql.Date


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

7. 利用NIO实现高速文件拷贝


public static void fileCopy( File in, File out ) 
      throws IOException 
  { 
    FileChannel inChannel = new FileInputStream( in ).getChannel(); 
    FileChannel outChannel = new FileOutputStream( out ).getChannel(); 
    try
    { 
//     inChannel.transferTo(0, inChannel.size(), outChannel);   // original -- apparently has trouble copying large files on Windows 
  
      // magic number for Windows, 64Mb - 32Kb) 
      int maxCount = (64 * 1024 * 1024) - (32 * 1024); 
      long size = inChannel.size(); 
      long position = 0; 
      while ( position < size ) 
      { 
        position += inChannel.transferTo( position, maxCount, outChannel ); 
      } 
    } 
    finally
    { 
      if ( inChannel != null ) 
      { 
        inChannel.close(); 
      } 
      if ( outChannel != null ) 
      { 
        outChannel.close(); 
      } 
    } 
  }

8. 生成图片的缩略图


private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename) 
    throws InterruptedException, FileNotFoundException, IOException 
  { 
    // load image from filename 
    Image image = Toolkit.getDefaultToolkit().getImage(filename); 
    MediaTracker mediaTracker = new MediaTracker(new Container()); 
    mediaTracker.addImage(image, 0); 
    mediaTracker.waitForID(0); 
    // use this to test for errors at this point: System.out.println(mediaTracker.isErrorAny()); 
  
    // determine thumbnail size from WIDTH and HEIGHT 
    double thumbRatio = (double)thumbWidth / (double)thumbHeight; 
    int imageWidth = image.getWidth(null); 
    int imageHeight = image.getHeight(null); 
    double imageRatio = (double)imageWidth / (double)imageHeight; 
    if (thumbRatio < imageRatio) { 
      thumbHeight = (int)(thumbWidth / imageRatio); 
    } else { 
      thumbWidth = (int)(thumbHeight * imageRatio); 
    } 
  
    // draw original image to thumbnail image object and 
    // scale it to the new size on-the-fly 
    BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); 
    Graphics2D graphics2D = thumbImage.createGraphics(); 
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); 
    graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); 
  
    // save thumbnail image to outFilename 
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename)); 
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); 
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); 
    quality = Math.max(0, Math.min(quality, 100)); 
    param.setQuality((float)quality / 100.0f, false); 
    encoder.setJPEGEncodeParam(param); 
    encoder.encode(thumbImage); 
    out.close(); 
  }

9. 构建JSON格式的数据结构

并下载这个JAR 文件:json-rpc-1.0.jar (75 kb)/http://t.cn/Rz0bhUA


import org.json.JSONObject; 
... 
... 
JSONObject json = new JSONObject(); 
json.put("city", "Mumbai"); 
json.put("country", "India"); 
... 
String output = json.toString(); 
...

10. 借助iText JAR库生成PDF文档


import java.io.File; 
import java.io.FileOutputStream; 
import java.io.OutputStream; 
import java.util.Date; 
  
import com.lowagie.text.Document; 
import com.lowagie.text.Paragraph; 
import com.lowagie.text.pdf.PdfWriter; 
  
public class GeneratePDF { 
  
  public static void main(String[] args) { 
    try { 
      OutputStream file = new FileOutputStream(new File("C:\\Test.pdf")); 
  
      Document document = new Document(); 
      PdfWriter.getInstance(document, file); 
      document.open(); 
      document.add(new Paragraph("Hello Kiran")); 
      document.add(new Paragraph(new Date().toString())); 
  
      document.close(); 
      file.close(); 
  
    } catch (Exception e) { 
  
      e.printStackTrace(); 
    } 
  } 
}

11. 配置HTTP代理设置


System.getProperties().put("http.proxyHost", "someProxyURL"); 
System.getProperties().put("http.proxyPort", "someProxyPort"); 
System.getProperties().put("http.proxyUser", "someUserName"); 
System.getProperties().put("http.proxyPassword", "somePassword");

12. 实现单实例Singleton模式的示例


public class SimpleSingleton { 
  private static SimpleSingleton singleInstance = new SimpleSingleton(); 
  
  //Marking default constructor private 
  //to avoid direct instantiation. 
  private SimpleSingleton() { 
  } 
  
  //Get instance for class SimpleSingleton 
  public static SimpleSingleton getInstance() { 
  
    return singleInstance; 
  } 
}

13. 编写抓屏程序


import java.awt.Dimension; 
import java.awt.Rectangle; 
import java.awt.Robot; 
import java.awt.Toolkit; 
import java.awt.image.BufferedImage; 
import javax.imageio.ImageIO; 
import java.io.File; 
  
... 
  
public void captureScreen(String fileName) throws Exception { 
  
  Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 
  Rectangle screenRectangle = new Rectangle(screenSize); 
  Robot robot = new Robot(); 
  BufferedImage image = robot.createScreenCapture(screenRectangle); 
  ImageIO.write(image, "png", new File(fileName)); 
  
} 
...

14. 列出指定目录下的文件和子目录


File dir = new File("directoryName"); 
 String[] children = dir.list(); 
 if (children == null) { 
   // Either dir does not exist or is not a directory 
 } else { 
   for (int i=0; i < children.length; i++) { 
     // Get filename of file or directory 
     String filename = children[i]; 
   } 
 } 
  
 // It is also possible to filter the list of returned files. 
 // This example does not return any files that start with `.'. 
 FilenameFilter filter = new FilenameFilter() { 
   public boolean accept(File dir, String name) { 
     return !name.startsWith("."); 
   } 
 }; 
 children = dir.list(filter); 
  
 // The list of files can also be retrieved as File objects 
 File[] files = dir.listFiles(); 
  
 // This filter only returns directories 
 FileFilter fileFilter = new FileFilter() { 
   public boolean accept(File file) { 
     return file.isDirectory(); 
   } 
 }; 
 files = dir.listFiles(fileFilter);

15. 创建ZIP和JAR归档文件


import java.util.zip.*; 
import java.io.*; 
  
public class ZipIt { 
  public static void main(String args[]) throws IOException { 
    if (args.length < 2) { 
      System.err.println("usage: java ZipIt Zip.zip file1 file2 file3"); 
      System.exit(-1); 
    } 
    File zipFile = new File(args[0]); 
    if (zipFile.exists()) { 
      System.err.println("Zip file already exists, please try another"); 
      System.exit(-2); 
    } 
    FileOutputStream fos = new FileOutputStream(zipFile); 
    ZipOutputStream zos = new ZipOutputStream(fos); 
    int bytesRead; 
    byte[] buffer = new byte[1024]; 
    CRC32 crc = new CRC32(); 
    for (int i=1, n=args.length; i < n; i++) { 
      String name = args[i]; 
      File file = new File(name); 
      if (!file.exists()) { 
        System.err.println("Skipping: " + name); 
        continue; 
      } 
      BufferedInputStream bis = new BufferedInputStream( 
        new FileInputStream(file)); 
      crc.reset(); 
      while ((bytesRead = bis.read(buffer)) != -1) { 
        crc.update(buffer, 0, bytesRead); 
      } 
      bis.close(); 
      // Reset to beginning of input stream 
      bis = new BufferedInputStream( 
        new FileInputStream(file)); 
      ZipEntry entry = new ZipEntry(name); 
      entry.setMethod(ZipEntry.STORED); 
      entry.setCompressedSize(file.length()); 
      entry.setSize(file.length()); 
      entry.setCrc(crc.getValue()); 
      zos.putNextEntry(entry); 
      while ((bytesRead = bis.read(buffer)) != -1) { 
        zos.write(buffer, 0, bytesRead); 
      } 
      bis.close(); 
    } 
    zos.close(); 
  } 
}

16. 解析或读取XML 文件

XML文件


<?xml version="1.0"?> 
 
   
    John 
    B 
    12 
   
   
    Mary 
    A 
    11 
   
   
    Simon 
    A 
    18 
   

Java代码


package net.viralpatel.java.xmlparser; 
  
import java.io.File; 
import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
  
import org.w3c.dom.Document; 
import org.w3c.dom.Element; 
import org.w3c.dom.Node; 
import org.w3c.dom.NodeList; 
  
public class XMLParser { 
  
  public void getAllUserNames(String fileName) { 
    try { 
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
      DocumentBuilder db = dbf.newDocumentBuilder(); 
      File file = new File(fileName); 
      if (file.exists()) { 
        Document doc = db.parse(file); 
        Element docEle = doc.getDocumentElement(); 
  
        // Print root element of the document 
        System.out.println("Root element of the document: "
            + docEle.getNodeName()); 
  
        NodeList studentList = docEle.getElementsByTagName("student"); 
  
        // Print total student elements in document 
        System.out 
            .println("Total students: " + studentList.getLength()); 
  
        if (studentList != null && studentList.getLength() > 0) { 
          for (int i = 0; i < studentList.getLength(); i++) { 
  
            Node node = studentList.item(i); 
  
            if (node.getNodeType() == Node.ELEMENT_NODE) { 
  
              System.out 
                  .println("====================="); 
  
              Element e = (Element) node; 
              NodeList nodeList = e.getElementsByTagName("name"); 
              System.out.println("Name: "
                  + nodeList.item(0).getChildNodes().item(0) 
                      .getNodeValue()); 
  
              nodeList = e.getElementsByTagName("grade"); 
              System.out.println("Grade: "
                  + nodeList.item(0).getChildNodes().item(0) 
                      .getNodeValue()); 
  
              nodeList = e.getElementsByTagName("age"); 
              System.out.println("Age: "
                  + nodeList.item(0).getChildNodes().item(0) 
                      .getNodeValue()); 
            } 
          } 
        } else { 
          System.exit(1); 
        } 
      } 
    } catch (Exception e) { 
      System.out.println(e); 
    } 
  } 
  public static void main(String[] args) { 
  
    XMLParser parser = new XMLParser(); 
    parser.getAllUserNames("c:\\test.xml"); 
  } 
}

17. 将Array数组转换为Map映射


import java.util.Map; 
import org.apache.commons.lang.ArrayUtils; 
  
public class Main { 
  
 public static void main(String[] args) { 
  String[][] countries = { { "United States", "New York" }, { "United Kingdom", "London" }, 
    { "Netherland", "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" } }; 
  
  Map countryCapitals = ArrayUtils.toMap(countries); 
  
  System.out.println("Capital of Japan is " + countryCapitals.get("Japan")); 
  System.out.println("Capital of France is " + countryCapitals.get("France")); 
 } 
}

18. 发送邮件通知


import javax.mail.*; 
import javax.mail.internet.*; 
import java.util.*; 
  
public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException 
{ 
  boolean debug = false; 
  
   //Set the host smtp address 
   Properties props = new Properties(); 
   props.put("mail.smtp.host", "smtp.example.com"); 
  
  // create some properties and get the default Session 
  Session session = Session.getDefaultInstance(props, null); 
  session.setDebug(debug); 
  
  // create a message 
  Message msg = new MimeMessage(session); 
  
  // set the from and to address 
  InternetAddress addressFrom = new InternetAddress(from); 
  msg.setFrom(addressFrom); 
  
  InternetAddress[] addressTo = new InternetAddress[recipients.length]; 
  for (int i = 0; i < recipients.length; i++) 
  { 
    addressTo[i] = new InternetAddress(recipients[i]); 
  } 
  msg.setRecipients(Message.RecipientType.TO, addressTo); 
  
  // Optional : You can also set your custom headers in the Email if you Want 
  msg.addHeader("MyHeaderName", "myHeaderValue"); 
  
  // Setting the Subject and Content Type 
  msg.setSubject(subject); 
  msg.setContent(message, "text/plain"); 
  Transport.send(msg); 
}

19. 发送携带数据的HTTP请求


import java.io.BufferedReader; 
import java.io.InputStreamReader; 
import java.net.URL; 
  
public class Main { 
  public static void main(String[] args) { 
    try { 
      URL my_url = new URL("http://coolshell.cn/"); 
      BufferedReader br = new BufferedReader(new InputStreamReader(my_url.openStream())); 
      String strTemp = ""; 
      while(null != (strTemp = br.readLine())){ 
      System.out.println(strTemp); 
    } 
    } catch (Exception ex) { 
      ex.printStackTrace(); 
    } 
  } 
}

20. 动态改变数组的大小

/** 
* Reallocates an array with a new size, and copies the contents 
* of the old array to the new array. 
* @param oldArray the old array, to be reallocated. 
* @param newSize the new array size. 
* @return A new array with the same contents. 
*/
private static Object resizeArray (Object oldArray, int newSize) { 
 int oldSize = java.lang.reflect.Array.getLength(oldArray); 
 Class elementType = oldArray.getClass().getComponentType(); 
 Object newArray = java.lang.reflect.Array.newInstance( 
 elementType,newSize); 
 int preserveLength = Math.min(oldSize,newSize); 
 if (preserveLength > 0) 
 System.arraycopy (oldArray,0,newArray,0,preserveLength); 
 return newArray; 
} 
 
// Test routine for resizeArray(). 
public static void main (String[] args) { 
 int[] a = {1,2,3}; 
 a = (int[])resizeArray(a,5); 
 a[3] = 4; 
 a[4] = 5; 
 for (int i=0; i

以上所述就是本文的全部内容了,希望大家能够喜欢。

上一篇
Spring Boot整合WebSocket实现群聊思路代码详解

本文介绍基于Spring Boot 2.3.10.RELEASE与Java 8,通过引入spring-boot-starter-websocket依赖实现即时通讯群聊功能。核心逻辑包含配置ServerEndpointExporter、使用@OnOpen等注解处理连接生命周期,并利用ConcurrentHashMap维护Session映射以实现消息广播推送。

下一篇
Java实现数字转成英文的方法

该Java工具类通过按三位一组分割数字字符串,结合预定义的英文数词表和单位数组,逐段解析并拼接出对应的英文表达。核心逻辑涵盖个位、十位及百位以上的单位追加,最终返回修剪后的完整英文字符串。

相关文章

更多
PHP实现JSON格式校验与特殊字符处理工具函数

本文提供了一组用于PHP环境下的数据处理辅助函数。核心功能包括通过`json_decode`结合错误捕获机制来验证JSON字符串的合法性,以及针对包含汉字和特殊字符的数据进行URL编码后安全转换为JSON格式的自定义方法。此外,还包含了静态资源路径存在性校验、多维数组特定字段检索及特定标点符号过滤等实用逻辑,旨在解决复杂数据序列化过程中的常见兼容性问题。

2026.01.21 988
PHP文件操作指南:fopen、fclose、feof、fgets与fwrite详解

本文详细介绍PHP中常用的文件读写内置函数,包括fopen打开文件、fclose关闭连接、feof检测末尾、fgets读取行及fwrite写入内容。通过语法说明与代码示例,帮助开发者掌握PHP文件处理的核心技巧。

2026.01.17 968
PHP嵌套数组处理JSON对象与数组的拼接及解析

本文介绍在PHP中利用嵌套数组处理包含对象和数组的混合JSON数据的方法。通过json_decode将JSON字符串转换为对象或数组,可灵活访问嵌套字段;使用json_encode可将PHP数组重新序列化为JSON格式。示例展示了如何解析含联系信息的对象及含多条记录的对象数组,并提取特定属性值。

2025.01.01 915
PHP处理JSON反斜杠及json_encode转义控制详解

本文介绍在PHP中处理JSON字符串时常见的反斜杠转义问题。当通过AJAX传输JSON数据时,常需使用stripslashes()函数清除多余的反斜杠,随后调用json_decode进行解码。此外,针对PHP 5.4及以上版本,可通过在json_encode中添加JSON_UNESCAPED_SLASHES参数,避免斜杠被自动转义,从而节省存储空间并提升可读性。

2026.05.01 866
Java删除文件失败排查:流未关闭与ZipFile资源释放

在Java开发中,执行file.delete()删除文件或文件夹时若返回false,通常由资源未释放引起。本文梳理了三种常见场景:非空文件夹、进程占用及流未关闭。重点指出在使用java.util.zip.ZipFile处理压缩文件时,必须显式调用close()方法以释放底层句柄,否则即使其他流已关闭,文件仍无法被删除。

2025.09.01 825
PHP 5.2+ JSON 处理详解:编码、解码与常见错误

自 PHP 5.2 版本起,原生提供了 json_encode() 和 json_decode() 函数用于处理 JSON 数据。json_encode() 负责将数组或对象转换为 JSON 字符串,需注意 UTF-8 编码要求及索引/关联数组的转换差异;json_decode() 则将 JSON 文本还原为 PHP 对象或关联数组。本文详细解析了类实例转换时的属性可见性限制,以及 JSON 语法中关于引号、键名和尾随逗号的常见报错原因。

2026.08.22 818

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。