20个非常有用的Java程序片段

转载自    20个非常有用的Java程序片段

下面是20个非常有用的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)

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;  }  
} 

另一种实现

public enum SimpleSingleton {  INSTANCE;  public void doSomething() {  }  
}  //Call the method from Singleton:  
SimpleSingleton.INSTANCE.doSomething(); 

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"?> 
<students> <student> <name>John</name> <grade>B</grade> <age>12</age> </student> <student> <name>Mary</name> <grade>A</grade> <age>11</age> </student> <student> <name>Simon</name> <grade>A</grade> <age>18</age> </student> 
</students> 

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("https://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<a.length; i++)  System.out.println (a[i]);  
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/328142.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

从工程转向管理,访谈Github公司的Phil Haack

在本次播客中&#xff0c;QCon旧金山大会、 伦敦大会和纽约大会的主席Wes Reisz访谈了GitHub的工程主管Phil Haack&#xff0c;Haack在Github的工作聚焦于实现将软件推送到开发人员的桌面&#xff0c;当前正致力于发布GitHub Desktop这样的软件。GitHub Desktop是用于Visual St…

怎样往阿里云windows服务器传文件

怎样往阿里云windows服务器传文件 2017年12月05日 21:28:56 阿杜_ardo 阅读数 9169 1、在本地电脑上&#xff0c;快捷键“WINR"在“运行”中输入“MSTSC”&#xff0c;点击确定。 2、在“远程桌面连接”框框点击“选项”展开。&#xff08;计算机中输入阿里云服务器的IP地…

Hibernate基本概念

--用户解锁alter user scott account unlock;一个项目对应一个表空间oracle:--创建表空间--创建用户create user 用户名idendified by 密码default tablespace 表空间名-- 授权grant 权限(角色) to 用户--建表--增删改查--存储过程对象 ->jdbc->数据库&#xff08;表…

手机app 服务器 网页同步,手机app接入云服务器

手机app接入云服务器 内容精选换一换通过内网连接云手机实例时&#xff0c;需要在租户VPC中创建一台弹性云服务器&#xff0c;作为连接云手机的跳板机器。若创建云手机服务器时未使用自定义网络&#xff0c;还需在云手机租户的VPC和服务器所在VPC之间建立对等连接&#xff0c;如…

Java中的OutOfMemoryError

转载自 Java中的OutOfMemoryError引子&#xff1a;今天在<Sharding-JDBC官方群>里有个哥们称“不连sjdbc不会把内存吃光&#xff0c;连sjdbc跑一会就把内存吃光”&#xff0c;倍感诧异&#xff0c;我们已经用sj很久了&#xff0c;一直未发现sj吃内存的情况&#xff0c;遂…

沉沦17年,这位昔日科技霸主、最值钱企业,终于回来了……

1999年12月30日&#xff0c;这是微软最高光的时刻。当天其股价创出历史最高位59.97美元/股&#xff0c;市值达到了6130亿美元&#xff0c;是有史以来最值钱的公司——直至13年后&#xff0c;苹果公司的市值才超越这一纪录。 ▲微软股价 处在新千年之交&#xff0c;意气风发的微…

mysql5.5安装配置 在阿里云服务器上 本地navicat连接

MySQL 5.5安装配置教程. 2018年03月20日 19:18:49 沸点数据 阅读数 18046 1、官网下载MySQL 5.5。 下载地址&#xff1a;https://dev.mysql.com/downloads/mysql/5.5.html#downloads 2、安装MySQL5.5 注意&#xff1a;安装之前&#xff0c;请关闭杀毒软件。 &#xff08;1…

Hibernate基本概念 (2)

框架&#xff1a;1.一个应用程序的半成品2.提供了一系列可以重用的API3.能开发效率更高&#xff0c;性能更好的项目Hibernate:持久化&#xff08;jdbc&#xff09; ORM( 对象 关系 映射)hibernate环境搭建1.导包&#xff1a;核心包&#xff0c;必须包&#xff0c;数据驱动包2…

通过网页查看服务器算法,java分析html算法(java网页蜘蛛算法示例)

遇到复杂而繁琐的html页面大家都望而却步。因为很难获取到相应的数据。最古老的办法的是尝试用正则表达式&#xff0c;估计那么繁琐的东西得不偿失&#xff0c;浪费我们宝贵的时间。第二个办法用开源组织htmlparser的包&#xff0c;这个是一个比较老的项目&#xff0c;但是效果…

JVM 调优系列之监控工具

转载自 JVM 调优系列之监控工具 摘要: 项目部署线上之后&#xff0c;我们该如何基于监控工具来快速定位问题.... 通过上一篇的jvm垃圾回收知识&#xff0c;我们了解了jvm对内存分配以及垃圾回收是怎么来处理的。理论是指导实践的工具&#xff0c;有了理论指导&#xff0c;定位…

写给开发者:记录日志的10个建议

尽管在写这篇博文的时候&#xff0c;我是在负责运维工作&#xff0c;不过本文主要是写给开发者的。 对我来说&#xff0c;明白如何记录日志和记录什么&#xff0c;是软件工程师必须明了的最艰巨的任务之一。之所以这么说&#xff0c;是因为这项任务与预测&#xff08;divinatio…

解决org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)错误

解决org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)错误 2018年07月23日 16:55:42 犹抱琵琶半遮面 阅读数 29677 &#xff01;&#xff01;&#xff01;此类问题出现的原因是——不细心 一般的原因 Mapper interface和xml文件的定义对应…

Java 9 中的 GC 调优基础

转载自 Java 9 中的 GC 调优基础在经过了几次跳票之后&#xff0c;Java 9终于在原计划日期的整整一年之后发布了正式版。Java 9引入了很多新的特性&#xff0c;除了闪瞎眼的Module System和REPL&#xff0c;最重要的变化我认为是默认GC&#xff08;Garbage Collector&#xf…

mysql删除索引 增加索引

使用ALTER TABLE语句创建索引alter table table_name add index index_name (column_list) ; alter table table_name add unique (column_list) ; alter table table_name add primary key (column_list) ;删除索引drop index index_name on table_name ; alter table table_n…

Hibernate基本概念 (3)

一、hibernate配置&#xff1a;1.导jar包2.配置主文件a。数据库连接 url 驱动 用户名&#xff0c;密码&#xff0c;方言b。相关 显示sql&#xff0c;sql格式化c。映射文件3.映射文件表到实体 字段到属性查询&#xff1a;select dname from Dept d;参数&#xff1a;1.按位置&…

全自动迁移数据库的实现 (Fluent NHibernate, Entity Framework Core)

在开发涉及到数据库的程序时&#xff0c;常会遇到一开始设计的结构不能满足需求需要再添加新字段或新表的情况&#xff0c;这时就需要进行数据库迁移。实现数据库迁移有很多种办法&#xff0c;从手动管理各个版本的ddl脚本&#xff0c;到实现自己的migrator&#xff0c;或是使用…

ThreadLocal 内存泄露的实例分析

转载自 ThreadLocal 内存泄露的实例分析前言 昨天分享了一篇深入分析 ThreadLocal 内存泄漏问题是从理论上分析ThreadLocal的内存泄漏问题&#xff0c;这一篇文章我们来分析一下实际的内存泄漏案例。分析问题的过程比结果更重要&#xff0c;理论结合实际才能彻底分析出内存泄…

ZKWeb网站框架的动态编译的实现原理

ZKWeb网站框架是一个自主开发的网页框架&#xff0c;实现了动态插件和自动编译功能。ZKWeb把一个文件夹当成是一个插件&#xff0c;无需使用csproj或xproj等形式的项目文件管理&#xff0c;并且支持修改插件代码后自动重新编译加载。 下面将说明ZKWeb如何实现这个功能&#xff…

Hibernate基本概念 (4)

一、缓存&#xff1a;提高性能1.一级缓存&#xff1a;session级别 一个session共享2.二级缓存&#xff1a;进程或群集级别 不同session可以共享步骤&#xff1a;1.导jar包 2.添加xml放到src3.配置hibernate.cfg.xmla.开启二级缓存b。缓存管理类4.配置持久化类使用二级缓存 3…

Java中的内存泄露的几种可能

转载自 Java中的内存泄露的几种可能Java内存泄漏引起的原因&#xff1a;内存泄漏是指无用对象&#xff08;不再使用的对象&#xff09;持续占有内存或无用对象的内存得不到及时释放&#xff0c;从而造成内存空间的浪费称为内存泄漏。长生命周期的对象持有短生命周期对象的引用…