分享一些非常有用的Java程序片段

分享一些非常有用的Java程序片段

向文件末尾添加内容 

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


单例模式

public class Singleton {

   private static Singleton instance = null;  

   private Singleton({  
   }  

   public static Singleton getInstance({  
       if (instance == null) {  
           instance = new Singleton();  
       }  
       return instance;  
   }  
}


将16进制字符串转换成字节数组

public static final byte[] toBytes(String s{
   byte[] bytes;
   bytes = new byte[s.length() / 2];
   for (int i = 0; i < bytes.length; i++) {
     bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2),
         16);
   }
   return bytes;
 }


将字节数组还原成16进制字符串

public static String toHexString(byte[] b) {
   StringBuffer sb = new StringBuffer(b.length * 2);
   for (int i = 0; i < b.length; i++) {
     sb.append(HEXCHAR[(b[i] & 0xf0) >>> 4]);
     sb.append(HEXCHAR[b[i] & 0x0f]);
   }
   return sb.toString();
 }


改变数组的大小 

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


把 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"));    
 }    
}


将字符串转换为Date类型

public static Date convertStringToDate(String strDate, String pattern) {
   if (StringUtil.isNull(strDate))
     return null;
   if (StringUtil.isNull(pattern))
     pattern = "yyyy-MM-dd HH:mm";
   SimpleDateFormat df = new SimpleDateFormat(pattern);
   try {
     return df.parse(strDate);
   } catch (ParseException e) {
     throw new KmssRuntimeException(e);
   }
 }


天数差

public static int diffDay(Date before, Date after) {
       return Integer.parseInt(String.valueOf(((after.getTime() - before.getTime()) / 86400000)));
   }


月数差

public static int diffMonth(Date before, Date after){
       int monthAll=0;
       int yearsX = diffYear(before,after);
       Calendar c1 = Calendar.getInstance();
       Calendar c2 = Calendar.getInstance();
       c1.setTime(before);
       c2.setTime(after);
       int monthsX = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
       monthAll=yearsX*12+monthsX;
       int daysX =c2.get(Calendar.DATE) - c1.get(Calendar.DATE);
       if(daysX>0){
           monthAll=monthAll+1;
       }
       return monthAll;
   }


时差

public static int diffHour(Date before, Date after){
      return (int)(after.getTime() - before.getTime())/1000/60/60;
  }


分差

public static int diffMinute(Date before, Date after){
      return (int)(after.getTime() - before.getTime())/1000/60;
  }


秒差

public static long diffSecond(Date before, Date after){
      return (after.getTime() - before.getTime())/1000;
  }


创建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();    
   }    
}


一些常用的效验

/**整数*/
private static final String intege="^-?[1-9]\\d*$";  
/** 正整数*/
private static final String intege1="^[1-9]\\d*$";          
/** 负整数*/
private static final String intege2="^-[1-9]\\d*$";          
/** 数字*/
private static final String num="^([+-]?)\\d*\\.?\\d+$";      
/** 正数(正整数 + 0)*/
private static final String num1="^[1-9]\\d*|0$";          
/** 负数(负整数 + 0)*/
private static final String num2="^-[1-9]\\d*|0$";          
/** 浮点数*/
private static final String decmal="^([+-]?)\\d*\\.\\d+$";      
/** 邮件*/
private static final String email="^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$"
/** 颜色*/
private static final String color="^[a-fA-F0-9]{6}$";        
/** url*/
private static final String url="^http[s]?=\\/\\/([\\w-]+\\.)+[\\w-]+([\\w-./?%&=]*)?$";  
/** 仅中文*/
private static final String chinese="^[\\u4E00-\\u9FA5\\uF900-\\uFA2D]+$";                                    
/**图片 */
private static final String picture="(.*)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$";  
/** 压缩文件*/
private static final String rar="(.*)\\.(rar|zip|7zip|tgz)$";                
/** 日期*/
private static final String date="^\\d{4}(\\-|\\/|\\.)\\d{1,2}\\1\\d{1,2}$";          
/** QQ号码*/
private static final String qq="^[1-9]*[1-9][0-9]*$";        
/** 电话号码的函数(包括验证国内区号;国际区号;分机号)*/
private static final String tel="^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{1,}))?$";  
/** 用来用户注册。匹配由数字、26个英文字母或者下划线组成的字符串*/
private static final String username="^\\w+$";            
/** 字母*/
private static final String letter="^[A-Za-z]+$";          
private static final String letterAndSpace="^[A-Za-z ]+$";          
/** 大写字母*/
private static final String letter_u="^[A-Z]+$";          
/** 小写字母*/
private static final String letter_l="^[a-z]+$";          
/** 身份证*/
private static final String idcard="^[1-9]([0-9]{14}|[0-9]{17})$";


发送邮件 

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


转自公众号:Java从入门到大神



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值