`

数据类型转换源码_zhuanzhuanzhuan

阅读更多

数据类型转换源码

文章分类:Java编程

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipOutputStream;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.log4j.Logger;
import org.apache.commons.lang.StringUtils;

import com.launch.x431.business.sysmanage.bizbean.SysManageFacade;

/**
 * <p>
 * Title: 表单字段的转化(乱码------>正常码)
 * </p>
 * <p>
 * Description: 数据类型转换
 * </p>
 * <p>
 * Copyright: Copyright (c) 2004
 * </p>
 * <p>
 * Company:
 * </p>
 *
 * @author xiao
 * @version 1.0
 */

public class ValueConvertor {
 private static Logger log = Logger.getLogger(ValueConvertor.class);

 public ValueConvertor() {
 }

 /**
  * 作用是把有乱码的中文字符串转化为正常的中文字符串
  *
  * @param str
  * @return
  */

 public static String toChineseString(String str) {
  String tmpString = null;
  try {
   tmpString = (str == null || str.equals("")) ? null : new String(
     str.trim().getBytes("8859_1"), "GB2312");
  } catch (Exception e) {
   log.error("Encoding Err...");
  }
  return tmpString;
 }

 /**
  * 作用是把有乱码的中文字符串转化为正常的中文字符串 系统(Tomcat)字符 转成 页面字符
  *
  * @param str
  * @return "" 在传值需要如此,而不是null
  */

 public static String toChineseString2(String str) {
  String tmpString = null;

  try {

   tmpString = (str == null || str.equals("")) ? "" : new String(
     str.trim().getBytes("GBK"),
     System.getProperty("file.encoding"));
  } catch (Exception e) {
   log.error("Encoding Err...");
  }

  return tmpString;
 }

 /**
  * 解决下载时 乱码问题
  *
  * @param s
  * @return
  */

 public static String toUtf8String(String s) {
  StringBuffer sb = new StringBuffer();
  for (int i = 0; i < s.length(); i++) {
   char c = s.charAt(i);
   if (c >= 0 && c <= 255) {
    sb.append(c);
   } else {
    byte[] b;
    try {

     b = Character.toString(c).getBytes("utf-8");

    } catch (Exception ex) {
     log.error(ex);
     b = new byte[0];
    }
    for (int j = 0; j < b.length; j++) {
     int k = b[j];
     if (k < 0)
      k += 256;
     sb.append("%" + Integer.toHexString(k).toUpperCase());
    }
   }
  }
  return sb.toString();
 }

 /**
  * 转成 BigDecimal类型
  *
  * @param str
  * @return
  */
 public static BigDecimal toBigDecimal(String str) {
  BigDecimal temp;

  temp = new BigDecimal((str == null || str.equals("")) ? "0" : str);

  return temp;
 }

 /**
  * 转成 Long类型
  *
  * @param str
  * @return
  */
 public static Long toLong(String str) {

  Long temp;
  temp = new Long((str == null || str.equals("")) ? "0" : str);
  return temp;
 }

 /**
  * 转成 Double类型
  *
  * @param str
  * @return
  */
 public static Double toDouble(String str) {

  Double temp;
  temp = new Double((str == null || str.equals("")) ? "0" : str);
  return temp;
 }

 /**
  * 转成 Date类型
  *
  * @param str
  * @return
  */
 public static Date toDate(String str) {

  Date temp;
  if (str == null || str.equals("")) {
   temp = new Date(System.currentTimeMillis());
   // log.error("日期 类型是 " +str);
  } else {
   // log.error("日期 类型是 " +str);
   temp = Date.valueOf(str);
  }

  return temp;
 }

 /**
  * Long 转成 String类型
  *
  * @param l
  * @return
  */
 public static String longtoString(Long longvalue) {
  String str = null;
  str = (null == longvalue) ? "" : longvalue.toString();
  return str;
 }

 /**
  * Date 转成 String类型
  *
  * @param datevalue
  * @return
  */
 public static String datetoString(java.util.Date datevalue) {
  String str = null;
  str = (null == datevalue) ? "" : datevalue.toString();
  return str;
 }

 /**
  * BigDecimal 转成 String 类型
  *
  * @param begdecimalvalue
  * @return
  */
 public static String bigdecimaltoString(BigDecimal begdecimalvalue) {
  String str = null;
  str = (null == begdecimalvalue) ? "" : begdecimalvalue.toString();
  return str;
 }

 /**
  * 判断是否为空类型
  *
  * @param str
  * @return
  */

 public static boolean notNull(String str) {
  return !(str == null || str.trim().equals(""));
 }

 /**
  * 判断是否为空类型
  *
  * @param str[]
  * @return
  */

 public static boolean notNull(String str[]) {
  return !(str == null || str.length <= 0);
 }

 /**
  * 为页面转化用 如果为空 转成空字符串
  *
  * @param str
  * @return
  */

 public static String objectToString(Object str) {
  if (str == null)
   return "";
  else
   return str.toString();
 }

 /**
  * 取BigDecimal对象的double类型值
  *
  * @param bigdecimalValue
  * @return
  */
 public static double getDoublevalue(BigDecimal bigdecimalValue) {
  if (bigdecimalValue == null)
   return 0;
  else
   return bigdecimalValue.doubleValue();
 }

 /**
  * 不为0或空的字符
  *
  * @param id
  * @return
  */
 public static boolean notZero(String id) {
  if (id == null || id.trim().equals("")) {
   return false;
  } else {
   if (id.equals("0"))
    return false;
   else
    return true;
  }
 }

 public static Integer toInteger(String id) {
  if (id == null || id.trim().equals("")) {
   return new Integer("0");
  } else {
   return new Integer(id);
  }
 }

 public static Integer toInteger2(String id) {
  if (id == null || id.trim().equals("")) {
   return null;
  } else {
   return new Integer(id);
  }
 }

 public static String longtoString(long id) {
  return String.valueOf(id);
 }

 public static Timestamp toTimestamp(String str) {

  Timestamp temp = null;

  // log.error("日期 类型是 " +str);
  if (str == null || str.equals("")) {
   temp = new Timestamp(System.currentTimeMillis());
  } else {
   try {
    if (str.length() > 10) {
     SimpleDateFormat formats = getSimpleDateFormat(
       Locale.CHINESE, 1);
     temp = new Timestamp(
       formats.parse(str.substring(0, 16)).getTime());
    } else {
     SimpleDateFormat formats = getSimpleDateFormat(
       Locale.CHINESE, 0);
     temp = new Timestamp(
       formats.parse(str.substring(0, 10)).getTime());
    }
   } catch (ParseException e) {
    log.error(e);
   }
  }

  return temp;

 }

 /**
  * 由 JS : new Date().getTimezoneOffset() 得到时区时间差值 转成
  *
  * @param timeZone_digital = new Date().getTimezoneOffset()
  * @return
  */
 public static TimeZone getTimeZone(String timeZone_digital) {
  String gmt = "";
  if (timeZone_digital != null) {
   int length = timeZone_digital.length();
   String d = "";
   String f = "";
   if (length == 1) {
    gmt = "GMT";
   } else if (timeZone_digital.startsWith("-")) {
    d = timeZone_digital.substring(0, 1);
    f = timeZone_digital.substring(1, length);
    gmt = "GMT+" + Integer.parseInt(f) / 60;
   } else {
    gmt = "GMT-" + Integer.parseInt(timeZone_digital) / 60;
   }

  } else {
   // 北京时区
   return TimeZone.getTimeZone("GMT+8");
  }

  return TimeZone.getTimeZone(gmt);
 }

 /**
  * HH:mm:ss 24小时制 hh:mm:ss 12小时制 SimpleDateFormat Locale loc int select
  * :日期格式精确度(0/1) 0: yyyy-mm-dd == 2005-02-01 1: yyyy-mm-dd HH:mm:ss ==
  * 2005-02-01 22:22:9
  */
 public static SimpleDateFormat getSimpleDateFormat(Locale loc, int select) {

  Locale default_locale = Locale.SIMPLIFIED_CHINESE;

  if (loc != null) {
   default_locale = loc;
  }

  SimpleDateFormat cnF = null;
  String default_pattern = "yyyy-MM-dd";

  String long_pattern = "yyyy-MM-dd HH:mm";

  if (select == 0) {
   cnF = new SimpleDateFormat(default_pattern, default_locale);
  } else if (select == 1) {
   cnF = new SimpleDateFormat(long_pattern, default_locale);
  } else {
   cnF = new SimpleDateFormat(default_pattern, default_locale);
  }

  return cnF;
 }

 // 国际化 转日期 : 日期 --> 字符
 /**
  * HH:mm:ss 24小时制 hh:mm:ss 12小时制 SimpleDateFormat Locale loc int select
  * :日期格式精确度(0/1) 0: yyyy-mm-dd == 2005-02-01 1: yyyy-mm-dd HH:mm:ss ==
  * 2005-02-01 22:22:9
  */
 public static String I18TimestampToStr(Timestamp times, Locale loc,
   String timeZone_digital, int select) {

  String temps = "";

  if (select == 0) {
   temps = I18TimestampToTimestamp(times, loc, timeZone_digital).toString().substring(
     0, 10);
  } else if (select == 1) {
   temps = I18TimestampToTimestamp(times, loc, timeZone_digital).toString().substring(
     0, 16);
  }

  return temps;

 }

 // yyyyMMdd == 20050201
 public static String formatDateForPayOnline(Timestamp times) {
  Locale default_locale = Locale.SIMPLIFIED_CHINESE;
  String default_pattern = "yyyyMMdd";
  SimpleDateFormat cnF = new SimpleDateFormat(default_pattern,
    default_locale);
  return cnF.format(times).substring(0, 8);
 }

 // 国际化 转日期 : 日期 --> 日期 (数据库数据 转 页面显示数据)
 /**
  * HH:mm:ss 24小时制 hh:mm:ss 12小时制 SimpleDateFormat Locale loc int select
  * :日期格式精确度(0/1) 0: yyyy-mm-dd == 2005-02-01 1: yyyy-mm-dd HH:mm:ss ==
  * 2005-02-01 22:22:9
  */
 public static Timestamp I18TimestampToTimestamp(Timestamp times,
   Locale loc, String timeZone_digital) {

  Timestamp tempDate = null;

  String temp = "";

  TimeZone zone = getTimeZone(timeZone_digital);

  SimpleDateFormat fullDateFormat = null;

  fullDateFormat = getSimpleDateFormat(loc, 1);

  // 以当地 时区转
  fullDateFormat.setTimeZone(zone);

  // log.error(zone.toString()+" :
  // "+fullDateFormat.toLocalizedPattern());
  if (times == null) {
   temp = fullDateFormat.format(new java.util.Date(
     System.currentTimeMillis()));
  } else {
   // System.out.println("input : " + times);
   temp = fullDateFormat.format(times);
   // System.out.println("convert : " + temp);
  }

  // 重新以 服务器时区转
  fullDateFormat.setTimeZone(TimeZone.getDefault());

  try {
   // System.out.println("convert : "+temp+" =
   // "+fullDateFormat.toPattern());
   tempDate = new Timestamp(fullDateFormat.parse(temp).getTime());

  } catch (ParseException e) {
   log.error("timestamp convert error", e);
  }

  return tempDate;
 }

 // 国际化 转日期 : 日期 --> 日期 (数据库数据 转 页面显示数据)
 /**
  * HH:mm:ss 24小时制 hh:mm:ss 12小时制 SimpleDateFormat Locale loc int select
  * :日期格式精确度(0/1) 0: yyyy-mm-dd == 2005-02-01 1: yyyy-mm-dd HH:mm:ss ==
  * 2005-02-01 22:22:9
  */
 public static Timestamp I18TimestampToTimestamp(Timestamp times,
   Locale loc, TimeZone zon) {

  Timestamp tempDate = null;

  String temp = "";

  TimeZone zone = zon;

  SimpleDateFormat fullDateFormat = null;

  fullDateFormat = getSimpleDateFormat(loc, 1);

  // 以当地 时区转
  fullDateFormat.setTimeZone(zone);

  // System.out.println("locale zone: "+TimeZone.getDefault().getID()+"
  // remote: "+zone.getID()+" format:
  // "+fullDateFormat.toLocalizedPattern());

  if (times == null) {
   temp = fullDateFormat.format(new java.util.Date(
     System.currentTimeMillis()));
  } else {
   // System.out.println("input : " + times);
   temp = fullDateFormat.format(times);
   // System.out.println("convert : " + temp);
  }
  // 重新以 服务器时区转
  fullDateFormat.setTimeZone(TimeZone.getDefault());

  try {

   tempDate = new Timestamp(fullDateFormat.parse(temp).getTime());

  } catch (ParseException e) {
   log.error("timestamp convert error", e);
  }

  return tempDate;
 }

 // 转字符 为 日期 (默认用中国大陆日期)
 /**
  * String times :字符表示的日期 int select : HH:mm:ss 24小时制 hh:mm:ss 12小时制
  * SimpleDateFormat Locale loc int select :日期格式精确度(0/1) 0: yyyy-mm-dd ==
  * 2005-02-01 1: yyyy-mm-dd HH:mm:ss == 2005-02-01 22:22:9
  */
 public static Timestamp I18StrToTimestamp(String times, Locale loc,
   String timeZone_digital, int select) {

  Timestamp temp = null;

  java.util.Date dd = null;

  Timestamp defaultDate = new Timestamp(System.currentTimeMillis());

  SimpleDateFormat cnF = null;

  TimeZone zone = getTimeZone(timeZone_digital);

  if (times == null || times.equals("")) {
   return defaultDate;
  } else {
   cnF = getSimpleDateFormat(loc, select);
   cnF.setTimeZone(zone);

   try {
    dd = cnF.parse(times);
   } catch (ParseException e) {
    log.error("timestamp convert error", e);
   }
  }
  // System.out.println(zone.getDisplayName()+" : "+times+" : "+dd);
  // return I18TimestampToTimestamp(new
  // Timestamp(dd.getTime()),Locale.CHINESE,timeZone_digital);
  return new Timestamp(dd.getTime());
 }

 /**
  * 产生随机数
  *
  * @param rands
  * @return
  */
 private static int getRandom(long rands) {
  return new Random(rands).nextInt();
 }

 /**
  * 生成订单号 ex:日期+时间 ex:FXO200512010301
  *
  * @return
  */
 private static final SimpleDateFormat sdf = new SimpleDateFormat(
   "yyyyMMddkkmmss");

 public synchronized static String gernateOrderNumber() {
  StringBuffer orderNo = new StringBuffer("FXO").append(sdf.format(new java.util.Date()));
  return orderNo.toString();
 }

 // 20080129 因为原来有重号 所以用了上面的
 public static String gernateOrderNumber1() {
  StringBuffer num = new StringBuffer();

  num.append("FXO");

  num.append(toDate(null).toString().substring(0, 4));
  num.append(toDate(null).toString().substring(5, 7));
  num.append(toDate(null).toString().substring(8, 10));

  num.append(toTimestamp(null).toString().substring(11, 13));
  num.append(toTimestamp(null).toString().substring(14, 16));

  // long tempN =getRandom(System.currentTimeMillis());
  // num.append((""+tempN).subSequence(1,5));

  // log.error("order: "+num.toString());

  return num.toString();
 }

 /**
  * 生成硬件配置(装箱单)号 ex:日期+时间 ex:FPL200512010301
  *
  * @return
  */
 public static String gernateHardConfNumber() {
  StringBuffer num = new StringBuffer();

  num.append("FPL");
  num.append(toDate(null).toString().substring(0, 4));
  num.append(toDate(null).toString().substring(5, 7));
  num.append(toDate(null).toString().substring(8, 10));

  num.append(toTimestamp(null).toString().substring(11, 13));
  num.append(toTimestamp(null).toString().substring(14, 16));

  // long tempN =getRandom(System.currentTimeMillis());
  // num.append((""+tempN).subSequence(1,5));

  // log.error("hardnu: "+num.toString());

  return num.toString();
 }

 /**
  * 生成 软件配置 号 ex:日期+时间 ex:XSC200512010301
  *
  * @return
  */
 public static String gernateSoftConfNumber() {
  StringBuffer num = new StringBuffer();
  num.append("XSC");
  num.append(toDate(null).toString().substring(0, 4));
  num.append(toDate(null).toString().substring(5, 7));
  num.append(toDate(null).toString().substring(8, 10));

  num.append(toTimestamp(null).toString().substring(11, 13));
  num.append(toTimestamp(null).toString().substring(14, 16));

  // long tempN =getRandom(System.currentTimeMillis());
  // num.append((""+tempN).subSequence(1,5));

  // log.error("softNu; "+num.toString());

  return num.toString();
 }

 /**
  * 货币格式化 处理
  *
  * @param loc
  * @param cur
  * @return
  */
 public static String currencyFormat(Locale loc, double cur) {
  String strcur = null;
  if (loc == null) {
   NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.SIMPLIFIED_CHINESE);
   strcur = nf.format(cur);
  } else {
   if (loc.getLanguage().equals(new Locale("zh", "", "").getLanguage())) {
    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.SIMPLIFIED_CHINESE);
    strcur = nf.format(cur);
   } else {
    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
    strcur = nf.format(cur);
   }

  }
  return strcur;
 }

 /**
  * 货币格式化 处理
  *
  * @param curId
  * @param cur
  * @return
  * @author zhangxiwang 2006-07-28
  */
 public static String currencyFormat(long curId, double cur) {
  String strcur = null;
  if (curId == Constants.CUR_ID_RMB) {
   NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.SIMPLIFIED_CHINESE);
   strcur = nf.format(cur);
  } else if (curId == 5) {
   NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.JAPAN);
   strcur = nf.format(cur);
  } else {
   NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
   strcur = nf.format(cur);

  }
  return strcur;
 }

 /**
  * 货币格式化 处理
  *
  * @param loc
  * @param cur
  * @return
  */
 public static String currencyFormat(String curCode, double cur) {
  String strcur = null;
  if (curCode != null) {
   if (curCode.equalsIgnoreCase("RMB")) {
    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.SIMPLIFIED_CHINESE);
    strcur = nf.format(cur);
   } else if (curCode.equalsIgnoreCase("USD")) {
    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
    strcur = nf.format(cur);
   } else if (curCode.equalsIgnoreCase("JPY")) {
    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.JAPAN);
    strcur = nf.format(cur);
   }
  } else {
   NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.SIMPLIFIED_CHINESE);
   strcur = nf.format(cur);
  }
  return strcur;
 }

 public static BigDecimal currencyFormat(int curId) {
  BigDecimal rate = null;
  switch (curId) {
  case 1:
   rate = new BigDecimal("1");
   break;
  case 2:
   rate = SysManageFacade.getSysManageFacade().searchExchangeRate(
     "USD", "RMB");

   break;
  case 5:
   BigDecimal usdTojPYBigDecimal = SysManageFacade.getSysManageFacade().searchExchangeRate(
     "USD", "JPY");
   BigDecimal usdToRmBigDecimal = SysManageFacade.getSysManageFacade().searchExchangeRate(
     "USD", "RMB");
   BigDecimal rmBigDecimal = new BigDecimal("1");

    rate = rmBigDecimal.divide(usdTojPYBigDecimal, 5,
     BigDecimal.ROUND_HALF_UP).multiply(usdToRmBigDecimal).setScale(
     5, BigDecimal.ROUND_HALF_UP);

   break;

  }
  return rate;

 }

 /**
  * 货币格式化 处理
  *
  * @param loc
  * @param cur
  * @return
  */
 public static String currencyFormat(String curCode, BigDecimal cur) {

  if (cur != null) {
   return currencyFormat(curCode, cur.doubleValue());
  } else {
   return currencyFormat(curCode, 0);
  }

 }

 /**
  * 货币格式化 处理
  *
  * @param loc
  * @param cur
  * @return
  */
 public static String currencyFormat(Locale loc, String cur) {

  String strcur = null;
  if (loc == null) {
   loc = Locale.SIMPLIFIED_CHINESE;
   NumberFormat nf = NumberFormat.getCurrencyInstance(loc);
   strcur = nf.format(toBigDecimal(cur).doubleValue());
  } else {
   strcur = currencyFormat(loc, toBigDecimal(cur).doubleValue());
  }
  return strcur;
 }

 /**
  * 重名文件 以系统时间
  *
  * @param pathName
  * @return
  */
 public static String reNameFile(String fileName) {
  String temp = null;
  if (fileName != null) {
   int index = fileName.indexOf(".");
   temp = System.currentTimeMillis() + "."
     + fileName.substring(index + 1, fileName.length());
  }
  return temp;
 }

 /**
  * 删除文件
  *
  * @param pathName
  * @return
  */
 public static boolean rmFile(String pathName) {
  if (IsExit(pathName)) {
   File dr = new File(pathName);
   return dr.delete();
  } else
   return false;
 }

 /**
  * 删除目录 (目录下有文件不删除)
  *
  * @param pathName
  * @return
  */
 public static boolean rmDirectory(String pathName) {
  if (IsExit(pathName)) {
   File dr = new File(pathName);
   if (dr.isDirectory()) {
    if (dr.listFiles() == null || dr.listFiles().length == 0) {
     return dr.delete();
    } else {
     return false;
    }
   } else {
    return dr.delete();
   }
  } else
   return false;
 }

 /**
  * 创建目录
  *
  * @param pathName
  * @return
  */
 public static boolean mkDirectory(String pathName) {
  if (IsExit(pathName)) {
   return false;
  } else {
   File dr = new File(pathName);
   dr.mkdir();
   return true;
  }
 }

 /**
  * 判断文件或目录是否存在
  *
  * @param pathName
  * @return
  */
 public static boolean IsExit(String pathName) {
  File virtualFile = new File(pathName);
  return virtualFile.exists();

 }

 /**
  * 根据操作系统 转换对应路径
  *
  * @param pathName
  * @return
  */
 public static String getFilePathByOperator(String pathName) {

  StringBuffer temp = new StringBuffer();

  // log.info("befor path == "+pathName + " os:
  // "+System.getProperty("os.name"));

  try {
   if (pathName != null) {
    if (SystemUtils.IS_OS_UNIX) {
     String[] s = StringUtils.split(pathName, "\\");

     if (s != null && s.length > 1) {
      for (int i = 0; i < s.length; i++) {
       temp.append("/");
       temp.append(s[i]);
      }

     } else {
      temp.append(pathName);
     }
    } else if (SystemUtils.IS_OS_WINDOWS) {
     String[] s = StringUtils.split(pathName, "/");
     if (s != null && s.length > 1) {
      for (int i = 0; i < s.length; i++) {
       temp.append("/");
       temp.append(s[i]);
      }
     } else {
      temp.append(pathName);
     }

    }
   }
  } catch (Exception e) {
   log.error(e);
  }
  // log.info("afer path == "+temp);

  return temp.toString();

 }

 /**
  * 压缩文件
  *
  * @param files 源文件(全路径文件)
  * @param fileNames (文件名称:用在压缩文件中)
  * @param destFile 目标文件
  * @param comments 压缩文件描述
  * @throws IOException
  */
 public static void zipFiles(String[] files, String[] fileNames,
   String destFile, String comments) throws IOException {

  try {
   FileOutputStream f = new FileOutputStream(destFile);
   // 算法 Adler32 运算速度快,CRC32 数据可信度好
   CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());

   ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
     csum));

   for (int i = 0; i < files.length; i++) {
    if (files[i] != null) {
     if (IsExit(files[i])) {
      FileInputStream in = new FileInputStream(new File(
        files[i]));

      // log.error(fileNames[i]);
      out.putNextEntry(new ZipEntry(fileNames[i]));

      int c;
      while ((c = in.read()) != -1) {
       out.write(c);
       // out.finish();
      }
      in.close();
     } else {
      throw new FileNotFoundException(files[i]);
     }
    }
   }
   // 检验值
   // log.info(String.valueOf(csum.getChecksum().getValue()));
   // 加描述
   out.setComment(comments);
   out.close();

  } catch (ZipException e) {
   log.error(e.getMessage());
   throw new IOException(e.getMessage());
  }

 }

 /**
  * 压缩文件
  * 相对于zipFiles增加输入缓冲流
  * 注释:// 算法 Adler32 运算速度快,CRC32 数据可信度好
  * @param files 源文件(全路径文件)
  * @param fileNames (文件名称:用在压缩文件中)
  * @param destFile 目标文件
  * @param comments 压缩文件描述
  * @throws IOException
  */
 public static void zipFiles2(String[] files, String[] fileNames,
   String destFile, String comments) throws IOException {
  try {
   int bufferSize = 2048;
   FileOutputStream f = null;
   CheckedOutputStream csum = null;
   ZipOutputStream out = null;
   
   try {
    f = new FileOutputStream(destFile);
    csum = new CheckedOutputStream(f, new Adler32());
    out = new ZipOutputStream(new BufferedOutputStream(csum));
    for (int i = 0; i < files.length; i++) {
     if (files[i] != null) {
      if (IsExit(files[i])) {
       FileInputStream in = null;
       BufferedInputStream bis = null;
       try {
        in = new FileInputStream(new File(files[i]));
        bis = new BufferedInputStream(in);
        out.putNextEntry(new ZipEntry(fileNames[i]));
        int count = 0;
        byte[] buffer = new byte[bufferSize];
        while ((count = bis.read(buffer, 0, bufferSize)) != -1) {
         out.write(buffer, 0, count);
        }
        
       }finally
       {
        if (in != null)
        {
         in.close();
        }
        if (bis != null)
        {
         bis.close();
        }
        
        
       }
       
      } else {
       throw new FileNotFoundException(files[i]);
      }
     }
     out.setComment(comments);

    }
   } finally {
    if (out != null) {
     out.close();
    }
   }

  } catch (Exception e) {
   throw new IOException(e);
  }

 }
 
 /**
  * 根据 IP (字符) 计算 数值 IP Number = A x 16777216 + B x 65536 + C x 256 + D
  *
  * @param ip (A.B.C.D)
  * @return
  */
 public static long ipCalculate(String ip) {
  long ipA = 0;
  if (ip != null) {
   StringTokenizer t = new StringTokenizer(ip, ".");
   if (t.hasMoreElements()) {
    ipA += Long.parseLong(t.nextToken()) * 16777216
      + Long.parseLong(t.nextToken()) * 65536
      + Long.parseLong(t.nextToken()) * 256
      + Long.parseLong(t.nextToken());
   }
  }
  // log.info("client IP: "+ip);
  return ipA;
 }

 /**
  * zh_CN 分解成 zh_,CN
  *
  * @param lan (zh_CN,zh_TW)
  * @return
  */
 public static String[] splitLanAndCountry(String lan) {
  String[] temp = new String[2];
  if (lan != null) {
   StringTokenizer t = new StringTokenizer(lan, "_");
   if (t.countTokens() > 1) {
    temp[0] = t.nextToken();
    temp[1] = t.nextToken();
   } else {
    temp[0] = t.nextToken();
    temp[1] = "";
   }
  }
  return temp;
 }

 public static void main(String[] args) {

  /*
   * Locale localeCN = Locale.SIMPLIFIED_CHINESE; Locale localeUSA =
   * Locale.US; TimeZone timeZoneMiami = TimeZone.getTimeZone("GMT-8");
   * Timestamp temp = new Timestamp(System.currentTimeMillis());
   * System.out.println("本地时间: " + temp + " 本地ID " +
   * timeZoneMiami.getID()); System.out.println("美国: " +
   * ValueConvertor.I18TimestampToStr(temp, localeUSA, "240", 1));
   * System.out.println("美国: " + ValueConvertor
   * .I18TimestampToTimestamp(temp, localeUSA, "240"));
   * System.out.println("2005-06-09 字符: " +
   * ValueConvertor.I18StrToTimestamp("2005-6-9", localeUSA, "240", 0));
   * System.out.println("2005-06-09 12:12 字符: " +
   * ValueConvertor.I18StrToTimestamp("2005-6-9 12:12:", localeUSA, "240",
   * 1));
   */

  /*
   * BigDecimal prices = new BigDecimal("0"); BigDecimal prices1 = new
   * BigDecimal(2); System.out.println("total: "+prices.doubleValue());
   * log.info("one is : "+prices1.doubleValue()); for(int i=0;i<10;i++)
   * System.out.println("plus is : "+prices.add(toBigDecimal(""+i)));
   * //System.out.println(toDate(null));
   * ValueConvertor.gernateOrderNumber();
   * ValueConvertor.gernateHardConfNumber();
   * ValueConvertor.gernateSoftConfNumber();
   */
  String[] files = { "D:/updateSofte/DADI_V11_00_CN_00361.ZIP",
    "D:/updateSofte/DADI_V11_00_CN_00368.ZIP" };
  String[] fileNames = { "DADI_V11_00_CN_00361.ZIP",
    "DADI_V11_00_CN_00368.ZIP" };

  String de = "D:/updateSofte/xx我.zip";

  try {
   ValueConvertor.zipFiles(files, fileNames, de, "x431-top");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  Calendar rightNow = Calendar.getInstance(Locale.CHINA);
  rightNow.add(Calendar.MONTH, 1);
  System.out.println("sss " + new Date(rightNow.getTimeInMillis()));

  String aa = "14.01";
  String bb = "19.0028999";
  String cc = "19.01";
  String dd = "19.00";

  BigDecimal copare = new BigDecimal(bb);
  /*
   * if((new BigDecimal(aa)).compareTo(copare)<0){ System.out.println("||
   * "+((new BigDecimal(aa)).compareTo(copare))); System.out.println("||
   * "+((new BigDecimal(cc)).compareTo(copare))); System.out.println("||
   * "+((new BigDecimal(dd)).compareTo(copare))); }
   */
  System.out.println("1 = " + copare + " 2= "
    + copare.setScale(2, BigDecimal.ROUND_HALF_UP));
  String serialNo = "980244601400";
  String version = "10.60";
  String softFlag = "SYSDATA";
  String pdtType = "X431";
  String softType = "4";
  String lanName = "中文简体";
  String carDeptName = "系统数据";
  String root = "D:\\workspace\\x431\\webapp\\download";
  String fileName = "DATA_V10_60_CN.ZIP";
  String sPath = root + "\\X431\\10.60\\DATA_V10_60_CN.ZIP ";

  StringBuffer x431_LicenseStr = new StringBuffer(serialNo).append("+").append(
    version).append("+").append(
    ValueConvertor.toChineseString2(softFlag))
  // +X431-X431TOP(X431,X431NANO) 产品系列-产品代号
  .append("+X431-").append(pdtType).append("+").append(softType).append(
    "+").append(lanName).append("+").append(
    ValueConvertor.toChineseString2(carDeptName)).append("+");

  StringBuffer oPath = new StringBuffer();

  oPath.append(root).append(File.separator).append("temp").append(
    File.separator).append(
    StringUtils.substringBeforeLast(fileName, ".")).append("_").append(
    serialNo.substring(5, 10)).append(".").append(
    StringUtils.substringAfterLast(fileName, "."));

  String licens = "980241570900+11.00+DFNISSAN+X431-X431+1+中文简体+东风日产+";
  String op = "D:\\workspace\\x431\\webapp\\download\\temp\\DFNISSAN_V11_00_CN_15709.ZIP";
  String sp = "D:\\workspace\\x431\\webapp\\download\\X431\\11.00\\DFNISSAN_V11_00_CN.ZIP";
  // int value = License.encryptData(oPath.toString(), sPath.toString(),
  // x431_LicenseStr.toString());
  // License.encryptData(op, sp, licens);
  String ids = "1,2,3,";
  String[] d = StringUtils.split(ids, ',');
  for (int i = 0; i < d.length; i++)
   System.out.println(d[i]);
 }

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics