收藏列表
标题 | 标签 | 来源 | |
文件处理函数 | 文件 | FileUtil(File处理工具类,copy,压缩,删除等) | |
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; 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.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.text.DateFormat; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.Locale; import java.util.StringTokenizer; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * * @author IBM * */ public class FileUtil { public static String dirSplit = "\\";//linux windows /** * save file accroding to physical directory infomation * * @param physicalDir * physical directory * @param fname * file name of destination * @param istream * input stream of destination file * @return */ public static boolean SaveFileByPhysicalDir(String physicalPath, InputStream istream) { boolean flag = false; try { OutputStream os = new FileOutputStream(physicalPath); int readBytes = 0; byte buffer[] = new byte[8192]; while ((readBytes = istream.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, readBytes); } os.close(); flag = true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return flag; } public static boolean CreateDirectory(String dir){ File f = new File(dir); if (!f.exists()) { f.mkdirs(); } return true; } public static void saveAsFileOutputStream(String physicalPath,String content) { File file = new File(physicalPath); boolean b = file.getParentFile().isDirectory(); if(!b){ File tem = new File(file.getParent()); // tem.getParentFile().setWritable(true); tem.mkdirs();// 创建目录 } //Log.info(file.getParent()+";"+file.getParentFile().isDirectory()); FileOutputStream foutput =null; try { foutput = new FileOutputStream(physicalPath); foutput.write(content.getBytes("UTF-8")); //foutput.write(content.getBytes()); }catch(IOException ex) { ex.printStackTrace(); throw new RuntimeException(ex); }finally{ try { foutput.flush(); foutput.close(); }catch(IOException ex){ ex.printStackTrace(); throw new RuntimeException(ex); } } //Log.info("文件保存成功:"+ physicalPath); } /** * COPY文件 * @param srcFile String * @param desFile String * @return boolean */ public boolean copyToFile(String srcFile, String desFile) { File scrfile = new File(srcFile); if (scrfile.isFile() == true) { int length; FileInputStream fis = null; try { fis = new FileInputStream(scrfile); } catch (FileNotFoundException ex) { ex.printStackTrace(); } File desfile = new File(desFile); FileOutputStream fos = null; try { fos = new FileOutputStream(desfile, false); } catch (FileNotFoundException ex) { ex.printStackTrace(); } desfile = null; length = (int) scrfile.length(); byte[] b = new byte[length]; try { fis.read(b); fis.close(); fos.write(b); fos.close(); } catch (IOException e) { e.printStackTrace(); } } else { scrfile = null; return false; } scrfile = null; return true; } /** * COPY文件夹 * @param sourceDir String * @param destDir String * @return boolean */ public boolean copyDir(String sourceDir, String destDir) { File sourceFile = new File(sourceDir); String tempSource; String tempDest; String fileName; File[] files = sourceFile.listFiles(); for (int i = 0; i < files.length; i++) { fileName = files[i].getName(); tempSource = sourceDir + "/" + fileName; tempDest = destDir + "/" + fileName; if (files[i].isFile()) { copyToFile(tempSource, tempDest); } else { copyDir(tempSource, tempDest); } } sourceFile = null; return true; } /** * 删除指定目录及其中的所有内容。 * @param dir 要删除的目录 * @return 删除成功时返回true,否则返回false。 */ public boolean deleteDirectory(File dir) { File[] entries = dir.listFiles(); int sz = entries.length; for (int i = 0; i < sz; i++) { if (entries[i].isDirectory()) { if (!deleteDirectory(entries[i])) { return false; } } else { if (!entries[i].delete()) { return false; } } } if (!dir.delete()) { return false; } return true; } /** * File exist check * * @param sFileName File Name * @return boolean true - exist<br> * false - not exist */ public static boolean checkExist(String sFileName) { boolean result = false; try { File f = new File(sFileName); //if (f.exists() && f.isFile() && f.canRead()) { if (f.exists() && f.isFile()) { result = true; } else { result = false; } } catch (Exception e) { result = false; } /* return */ return result; } /** * Get File Size * * @param sFileName File Name * @return long File's size(byte) when File not exist return -1 */ public static long getSize(String sFileName) { long lSize = 0; try { File f = new File(sFileName); //exist if (f.exists()) { if (f.isFile() && f.canRead()) { lSize = f.length(); } else { lSize = -1; } //not exist } else { lSize = 0; } } catch (Exception e) { lSize = -1; } /* return */ return lSize; } /** * File Delete * * @param sFileName File Nmae * @return boolean true - Delete Success<br> * false - Delete Fail */ public static boolean deleteFromName(String sFileName) { boolean bReturn = true; try { File oFile = new File(sFileName); //exist if (oFile.exists()) { //Delete File boolean bResult = oFile.delete(); //Delete Fail if (bResult == false) { bReturn = false; } //not exist } else { } } catch (Exception e) { bReturn = false; } //return return bReturn; } /** * File Unzip * * @param sToPath Unzip Directory path * @param sZipFile Unzip File Name */ @SuppressWarnings("rawtypes") public static void releaseZip(String sToPath, String sZipFile) throws Exception { if (null == sToPath ||("").equals(sToPath.trim())) { File objZipFile = new File(sZipFile); sToPath = objZipFile.getParent(); } ZipFile zfile = new ZipFile(sZipFile); Enumeration zList = zfile.entries(); ZipEntry ze = null; byte[] buf = new byte[1024]; while (zList.hasMoreElements()) { ze = (ZipEntry) zList.nextElement(); if (ze.isDirectory()) { continue; } OutputStream os = new BufferedOutputStream( new FileOutputStream(getRealFileName(sToPath, ze.getName()))); InputStream is = new BufferedInputStream(zfile.getInputStream(ze)); int readLen = 0; while ((readLen = is.read(buf, 0, 1024)) != -1) { os.write(buf, 0, readLen); } is.close(); os.close(); } zfile.close(); } /** * getRealFileName * * @param baseDir Root Directory * @param absFileName absolute Directory File Name * @return java.io.File Return file */ @SuppressWarnings({ "rawtypes", "unchecked" }) private static File getRealFileName(String baseDir, String absFileName) throws Exception { File ret = null; List dirs = new ArrayList(); StringTokenizer st = new StringTokenizer(absFileName, System.getProperty("file.separator")); while (st.hasMoreTokens()) { dirs.add(st.nextToken()); } ret = new File(baseDir); if (dirs.size() > 1) { for (int i = 0; i < dirs.size() - 1; i++) { ret = new File(ret, (String) dirs.get(i)); } } if (!ret.exists()) { ret.mkdirs(); } ret = new File(ret, (String) dirs.get(dirs.size() - 1)); return ret; } /** * copyFile * * @param srcFile Source File * @param targetFile Target file */ @SuppressWarnings("resource") static public void copyFile(String srcFile , String targetFile) throws IOException { FileInputStream reader = new FileInputStream(srcFile); FileOutputStream writer = new FileOutputStream(targetFile); byte[] buffer = new byte [4096]; int len; try { reader = new FileInputStream(srcFile); writer = new FileOutputStream(targetFile); while((len = reader.read(buffer)) > 0) { writer.write(buffer , 0 , len); } } catch(IOException e) { throw e; } finally { if (writer != null)writer.close(); if (reader != null)reader.close(); } } /** * renameFile * * @param srcFile Source File * @param targetFile Target file */ static public void renameFile(String srcFile , String targetFile) throws IOException { try { copyFile(srcFile,targetFile); deleteFromName(srcFile); } catch(IOException e){ throw e; } } public static void write(String tivoliMsg,String logFileName) { try{ byte[] bMsg = tivoliMsg.getBytes(); FileOutputStream fOut = new FileOutputStream(logFileName, true); fOut.write(bMsg); fOut.close(); } catch(IOException e){ //throw the exception } } /** * This method is used to log the messages with timestamp,error code and the method details * @param errorCd String * @param className String * @param methodName String * @param msg String */ public static void writeLog(String logFile, String batchId, String exceptionInfo) { DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.JAPANESE); Object args[] = {df.format(new Date()), batchId, exceptionInfo}; String fmtMsg = MessageFormat.format("{0} : {1} : {2}", args); try { File logfile = new File(logFile); if(!logfile.exists()) { logfile.createNewFile(); } FileWriter fw = new FileWriter(logFile, true); fw.write(fmtMsg); fw.write(System.getProperty("line.separator")); fw.flush(); fw.close(); } catch(Exception e) { } } public static String readTextFile(String realPath) throws Exception { File file = new File(realPath); if (!file.exists()){ System.out.println("File not exist!"); return null; } BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(realPath),"UTF-8")); String temp = ""; String txt=""; while((temp = br.readLine()) != null){ txt+=temp; } br.close(); return txt; } } |
|||
时间处理函数 | DateUtil(时间处理函数工具) | ||
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; /** * 时间处理函数 * * @20080509 15:50 */ public class DateUtil { private static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss"; public static final String TIME_YEAR = "yyyy"; public static final String TIME_MONEN = "MM"; public static final String TIME_DAY = "dd"; public static String getDate(String interval, Date starttime, String pattern) { Calendar temp = Calendar.getInstance(TimeZone.getDefault()); temp.setTime(starttime); temp.add(temp.MONTH, Integer.parseInt(interval)); SimpleDateFormat sdf = new SimpleDateFormat(pattern); return sdf.format(temp.getTime()); } /** * 将字符串类型转换为时间类型 * * @return */ public static Date str2Date(String str) { Date d = null; SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_PATTERN); try { d = sdf.parse(str); } catch (Exception e) { e.printStackTrace(); } return d; } public static Date str2Date(String str, String pattern) { Date d = null; SimpleDateFormat sdf = new SimpleDateFormat(pattern); try { d = sdf.parse(str); } catch (Exception e) { e.printStackTrace(); } return d; } /** * 将时间格式化 * * @return */ public static Date DatePattern(Date date) { SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_PATTERN); try { String dd = sdf.format(date); date = str2Date(dd); } catch (Exception e) { e.printStackTrace(); } return date; } /** * 将时间格式化 */ public static Date DatePattern(Date date, String pattern) { SimpleDateFormat sdf = new SimpleDateFormat(pattern); try { String dd = sdf.format(date); date = str2Date(dd, pattern); } catch (Exception e) { e.printStackTrace(); } return date; } public static String date2Str(Date date) { SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_PATTERN); return sdf.format(date); } public static String date2Str(Date date, String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf.format(date); } /** * 获取昨天 * * @param date * @return * @throws Exception */ public static Date getLastDate(Date date) { Calendar calendar = Calendar.getInstance(TimeZone.getDefault()); calendar.setTime(date); calendar.add(calendar.DATE, -1); return str2Date(date2Str(calendar.getTime())); } /** * 获取前几天 * @param date * @return */ public static Date getBeforeDate(Date date,int dates) { Calendar calendar = Calendar.getInstance(TimeZone.getDefault()); calendar.setTime(date); calendar.add(calendar.DATE, -dates); return str2Date(date2Str(calendar.getTime())); } /** * 获取上周第一天(周一) * * @param date * @return * @throws Exception */ public static Date getLastWeekStart(Date date) { Calendar calendar = Calendar.getInstance(TimeZone.getDefault()); calendar.setTime(date); int i = calendar.get(calendar.DAY_OF_WEEK) - 1; int startnum = 0; if (i == 0) { startnum = 7 + 6; } else { startnum = 7 + i - 1; } calendar.add(calendar.DATE, -startnum); return str2Date(date2Str(calendar.getTime())); } /** * 获取上周最后一天(周末) * * @param date * @return * @throws Exception */ public static Date getLastWeekEnd(Date date) { Calendar calendar = Calendar.getInstance(TimeZone.getDefault()); calendar.setTime(date); int i = calendar.get(calendar.DAY_OF_WEEK) - 1; int endnum = 0; if (i == 0) { endnum = 7; } else { endnum = i; } calendar.add(calendar.DATE, -(endnum - 1)); return str2Date(date2Str(calendar.getTime())); } /** * 根据年和月得到天数 * @param num 月 * @param year 年 * @return */ public static int getday(int num,int year){ if(num==1 || num==3 || num==5 || num==7 || num==8 || num==10 || num==12){ return 31; }else if(num==2){ //判断是否为闰年 if(year%400==0 || (year%4==0 && year%100!=0)){ return 29; }else{ return 28; } }else{ return 30; } } /* * 计算当前日期距离下个月还有多少天 */ public static int getdaymis(Date time){ int year = Integer.parseInt( new SimpleDateFormat(TIME_YEAR).format(time));//年 int mm = Integer.parseInt( new SimpleDateFormat(TIME_MONEN).format(time));//月 int dd = Integer.parseInt( new SimpleDateFormat(TIME_DAY).format(time));//日 //获取当前年月的总天数 int sdd = getday(mm,year); return sdd-dd; } /** * 日期转秒数 * @param dateString * @return */ public static long getTime(String dateString) { long time = 0; try { Date ret = null; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ret = sdf.parse(dateString); time = ret.getTime()/1000; } catch (Exception e) { } return time; } /** * 精确计算时间差,精确到日 * @param fistill 起始日期 * @param nowtime 结束日期 * @param type type为1返回年月日(如:2年3个月零5天) 否则返回总的天数 * @return */ public static String patienage(Date fistill,Date nowtime,Integer type){ int fyear = Integer.parseInt( new SimpleDateFormat(TIME_YEAR).format(fistill));//起始年 int fmm = Integer.parseInt( new SimpleDateFormat(TIME_MONEN).format(fistill));//起始月 int fdd = Integer.parseInt( new SimpleDateFormat(TIME_DAY).format(fistill));//起始日 int nyear = Integer.parseInt( new SimpleDateFormat(TIME_YEAR).format(nowtime));//结束年 int nmm = Integer.parseInt( new SimpleDateFormat(TIME_MONEN).format(nowtime));//结束月 int ndd = Integer.parseInt( new SimpleDateFormat(TIME_DAY).format(nowtime));//结束日 int cyear = nyear - fyear; int cmm = nmm - fmm; int cdd = ndd - fdd; int zyear = 0; int zmm = 0; int zdd = 0; int countddd = 0; //年月日累计天数 if(cdd<0){ if(cmm<0){ zyear = cyear - 1; zmm = (cmm + 12)-1; int dd = getday(zmm,nyear-1); zdd = dd + cdd; countddd = zyear*365+zmm*30+zdd; }else if(cmm==0){ zyear = cyear - 1; zmm = 12-1; int dd = getday(zmm,nyear-1); zdd = dd + cdd; countddd = zyear*365+zmm*30+zdd; }else{ zyear = cyear; zmm = cmm - 1; int dd = getday(zmm,nyear); zdd = dd + cdd; countddd = zyear*365+zmm*30+zdd; } }else if(cdd==0){ if(cmm<0){ zyear = cyear - 1; zmm = cmm + 12; zdd = 0; countddd = zyear*365+zmm*30; }else if(cmm==0){ zyear = cyear; zmm = 0; zdd = 0; countddd = zyear*365+zmm*30; }else{ zyear = cyear; zmm = cmm; zdd = 0; countddd = zyear*365+zmm*30; } }else{ if(cmm<0){ zyear = cyear - 1; zmm = cmm + 12; zdd = cdd; countddd = zyear*365+zmm*30+zdd; }else if(cmm==0){ zyear = cyear; zmm = 0; zdd = cdd; countddd = zyear*365+zmm*30+zdd; }else{ zyear = cyear; zmm = cmm; zdd = cdd; countddd = zyear*365+zmm*30+zdd; } } String ptime = null; if(zdd!=0){ if(zmm!=0){ if(zyear!=0){ ptime = zyear+"年"+zmm+"个月"+"零"+zdd+"天"; }else{ ptime = zmm+"个月"+"零"+zdd+"天"; } }else{ if(zyear!=0){ ptime = zyear+"年"+"零"+zdd+"天"; }else{ ptime = zdd+"天"; } } }else{ if(zmm!=0){ if(zyear!=0){ ptime = zyear+"年"+zmm+"个月"; }else{ ptime = zmm+"个月"; } }else{ if(zyear!=0){ ptime = zyear+"年"; }else{ ptime = null; } } } if(type==1){ return ptime; //返回年月日(如:2年3个月零5天) }else{ return String.valueOf(countddd); //返回总天数 } } /** * 得到月数 * @param year 年数差 * @param month 月数差 * @return */ public static int getCmm(Integer year,Integer month){ int zmm = 0; if(month < 0){ zmm = (month + 12)+(year-1)*12; }else if(month == 0){ zmm = year*12; }else{ zmm = year*12+month; } return zmm; } /** * 改更现在时间 */ public static Date changeDate(String type, int value) { Calendar calendar = Calendar.getInstance(TimeZone.getDefault()); if (type.equals("month")) { calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + value); } else if (type.equals("date")) { calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + value); } return calendar.getTime(); } /** * 更改时间 */ public static Date changeDate(Date date, String type, int value) { if (date != null) { // Calendar calendar = Calendar.getInstance(TimeZone.getDefault()); Calendar calendar = new GregorianCalendar(); calendar.setTime(date); // Calendar calendar = Calendar. if (type.equals("month")) { calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + value); } else if (type.equals("date")) { calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + value); } else if (type.endsWith("year")) { calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + value); } return calendar.getTime(); } return null; } /** * haoxw 比较时间是否在这两个时间点之间 * * @param time1 * @param time2 * @return */ public static boolean checkTime(String time1, String time2) { Calendar calendar = Calendar.getInstance(); Date date1 = calendar.getTime(); Date date11 = DateUtil.str2Date(DateUtil.date2Str(date1, "yyyy-MM-dd") + " " + time1);// 起始时间 Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, 1); Date date2 = c.getTime(); Date date22 = DateUtil.str2Date(DateUtil.date2Str(date2, "yyyy-MM-dd") + " " + time2);// 终止时间 Calendar scalendar = Calendar.getInstance(); scalendar.setTime(date11);// 起始时间 Calendar ecalendar = Calendar.getInstance(); ecalendar.setTime(date22);// 终止时间 Calendar calendarnow = Calendar.getInstance(); if (calendarnow.after(scalendar) && calendarnow.before(ecalendar)) { return true; } else { return false; } } /** * haoxw 比较时间是否在这两个时间点之间 * * @param date11 * @param date22 * @return */ public static boolean checkTime(Date date11, Date date22) { Calendar scalendar = Calendar.getInstance(); scalendar.setTime(date11);// 起始时间 Calendar ecalendar = Calendar.getInstance(); ecalendar.setTime(date22);// 终止时间 Calendar calendarnow = Calendar.getInstance(); if (calendarnow.after(scalendar) && calendarnow.before(ecalendar)) { return true; } else { return false; } } public static boolean checkDate(String date1, String date2) { Date date11 = DateUtil.str2Date(date1, "yyyy-MM-dd HH:mm:ss");// 起始时间 Date date22 = DateUtil.str2Date(date2, "yyyy-MM-dd HH:mm:ss");// 终止时间 Calendar scalendar = Calendar.getInstance(); scalendar.setTime(date11);// 起始时间 Calendar ecalendar = Calendar.getInstance(); ecalendar.setTime(date22);// 终止时间 Calendar calendarnow = Calendar.getInstance(); System.out.println(date11.toString()); System.out.println(date22.toString()); System.out.println(scalendar.toString()); System.out.println(ecalendar.toString()); System.out.println(calendarnow.toString()); if (calendarnow.after(scalendar) && calendarnow.before(ecalendar)) { return true; } else { return false; } } /** * 获取interval天之前的日期 * * @param interval * @param starttime * @param pattern * @return */ public static Date getIntervalDate(String interval, Date starttime, String pattern) { Calendar temp = Calendar.getInstance(); temp.setTime(starttime); temp.add(temp.DATE, Integer.parseInt(interval)); SimpleDateFormat sdf = new SimpleDateFormat(pattern); String shijian = sdf.format(temp.getTime()); return str2Date(shijian); } public static Date formatDate(Date date){ SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd"); System.out.println(bartDateFormat.format(date)); SimpleDateFormat bartDateFormat1 =new SimpleDateFormat("yyyy-MM-dd"); try { Date date1 = bartDateFormat1.parse(bartDateFormat.format(date)); } catch (ParseException e) { e.printStackTrace(); } System.out.println(date.getTime()); return date; } public static void main(String arf[]) { /*String time1 = "2009-05-07 19:20:00"; String time2 = "2009-05-08 19:30:00"; DateUtil d = new DateUtil(); System.out.println(d.checkDate(time1, time2)); System.out.println(d.date2Str(new Date()));*/ //System.out.println(d.getIntervalDate("-3", new Date(), DEFAULT_PATTERN)); Calendar calendar = Calendar.getInstance(TimeZone.getDefault()); System.out.println(calendar.toString()); System.out.println(DateUtil.str2Date("20090731","yyyyMMdd")); System.out.println(DateUtil.getBeforeDate(new Date(),2 )); System.out.println(DateUtil.DatePattern(new Date())); SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); System.out.println("date;"+bartDateFormat.format(date)); SimpleDateFormat bartDateFormat1 =new SimpleDateFormat("yyyy-MM-dd"); try { Date date1 = bartDateFormat1.parse(bartDateFormat.format(date)); System.out.println("日期:"+date1); } catch (ParseException e) { e.printStackTrace(); } } } |