Java 编程中常用到的工具函数

版权声明:本文为博主原创文章,未经博主允许不得转载。| www.changxuan.top | www.qingning99.cn | 公众号:Worldhello | https://blog.csdn.net/vcx08/article/details/83750545

在 Java 项目中可能会用到一些工具函数,比如获取两个日期的时间差等。下面的这些函数是我大二一个课程设计中用到自己编写的。为了防止浪费时间重复造轮子,然后分享出来吧。

课程设计:飞机订票系统
用 Java 写的数据结构课程设计,不知怎么的让 Java 老师知道了。然后。。。。天天督促我完善项目,比数据结构老师催的都紧,最后被 Java 老师拿走了。说是他去完善下文档,给学弟学妹们当课程设计模版,也没下文。不过还是挺有成就感的~~~

函数

某文件中有几条记录

    /**
      * 某文件中有几条记录
      * @param FILEPATH
      * @param filename
      * @return 
      */
     public static int readToLines(String FILEPATH,String filename) {
		int n = 0;
		String lineString = "";
		try {
			File  file = new File(FILEPATH+filename);
			FileReader fr = new FileReader(file);
			BufferedReader br = new BufferedReader(fr);
			while((lineString = br.readLine()) != null){
				n++;
			}
			fr.close();
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return n;
	}

获得当前日期-1(yyyy-MM-dd)

public static String getTime(){                                       
   	Date now = new Date();
   	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   	return sdf.format(now);
   	
}

获得当前日期-2(yyyy-MM-dd HH:mm:ss)

public static String getTime(){                                       
   	Date now = new Date();
   	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   	return sdf.format(now);
   }

生成订单编号

 /**
     * 产生订单编号
     * @param hangBanHao
     * @return 
     */
    public static String getDingDanID(String hangBanHao){  
    	//booking.txt 订单记录文件               
        int countDingDan = readToLines("./booking_record/","booking.txt");
        String count = "0";
        if(countDingDan < 10){
            count = count + count + count + countDingDan;
        }else if(countDingDan < 1000){
            count = count + count + countDingDan;
        }else if(countDingDan < 10000){
            return (hangBanHao + Tool.getTime() + countDingDan);
        }else{
            countDingDan = 0;
            count = count + count + count + countDingDan;
        }
        return (hangBanHao + Tool.getTime() + count);
    }

获得时间差

    /**
     * 返回飞行时间差,作为权值
     * @param startTime
     * @param endTime
     * @return 
     */
    public static long getPlayTime(String startTime,String endTime){      
        long timeLen = 0;
        DateFormat df = new SimpleDateFormat("HH:mm:ss");
        try{   
	        Date d1 = df.parse(endTime);   
	        Date d2 = df.parse(startTime);   
	        long diff = d1.getTime() - d2.getTime();   
	        long days = diff / (1000 * 60 );
	        timeLen = days;
        }catch (Exception e){
        }
        return timeLen;
    }

判断文件是否存在

/**
     * 判断文件是否存在,存在则返回 true 否则创建此文件并返回 false
     * @param file
     * @return 
     */
     public static boolean judeFileExists(File file) {
        if (file.exists()) {
            return true;
        } else {
            try {
                file.createNewFile();
            } catch (IOException ex) {
                Logger.getLogger(Operation.class.getName()).log(Level.SEVERE, null, ex);
            }
            return false;
        }
     }

判断文件夹中是否存在文件

/**
     * 判断文件夹中是否存在文件
     * @param path
     * @return 
     */
    public static boolean testDir(String path)
  {
    File f = new File(path);
     if (f.exists())
     {
        //System.out.println("文件夹中存在文件");
        return true;
     }
     else{
        //System.out.println("文件夹中不存在文件");
        return false;
     }
  }

获取 n 天前的日期

/**
     * 获取n天前的日期
     * @param n
     * @return 
     */
    public static String getBeforetime(int n){
        Date now=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
	    return sdf.format(new Date(now.getTime() -  n*24 * 60 * 60 * 1000));
    }

获取 n 天后的日期

 /**
      * 获取n天后的日期
      * @param n
      * @return 
      */
    public static String getAftertime(int n){
        Date now=new Date();
        GregorianCalendar gc=new GregorianCalendar(); 
        gc.setTime(new Date()); 
        gc.add(5,n); 
        gc.set(gc.get(Calendar.YEAR),gc.get(Calendar.MONTH),gc.get(Calendar.DATE));
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(gc.getTime());
       // 单纯的使用Data类进行加运算时容易出错
       // return sdf.format(new Date(now.getTime() +  n*24 * 60 * 60 * 1000));
    }

删除某个路径下的文件

 /**
     * 删除某路径下的文件
     * @param fileName (如:/var/www/html/test.java)
     */
    public static void deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
        if (file.exists() && file.isFile()) {
            //此处应该做异常处理,可是我不想处理
            file.delete();
            //System.out.println("删除单个文件" + fileName + "成功!");
              
        } else {
            //System.out.println("删除单个文件失败:" + fileName + "不存在!");
            System.out.println("程序删除文件异常!");
        }
    }

将file1 中的文件拷贝到file2 文件夹中

 /**
     * 将file1 中的文件拷贝到file2 文件夹中
     * 例      copy("./flight_information/flight_record.txt","./month_flight_information");
     * @param file1
     * @param file2 
     */
    public static void copy(String file1, String file2) {
	    //System.out.println(file1);
	    //System.out.println(file2);
	    File src=new File(file1);
	    File dst=new File(file2);
	    if(!dst.exists()){
	         dst.mkdirs();
	    }
	    InputStream in = null;
	    OutputStream out = null;
	    //System.out.println(file1.substring(file1.lastIndexOf("/"),file1.length()));//获取单个文件的源文件的名称
	    try {
            in = new BufferedInputStream(new FileInputStream(src), 16 * 1024);
            FileOutputStream f= new FileOutputStream(dst+file1.substring(file1.lastIndexOf("/"),file1.length()));//一定要加上文件名称
            out = new BufferedOutputStream(f, 16 * 1024);
            byte[] buffer = new byte[16 * 1024];
            int len = 0;
            while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
            }
	    } catch (Exception e) {
	            e.printStackTrace();
	    } finally {
	    if (null != in) {
		    try {
		    in.close();
		    } catch (IOException e) {
		    e.printStackTrace();
		    }
	    }
	    if (null != out) {
		    try {
		    out.close();
		    } catch (IOException e) {
		    e.printStackTrace();
	    }
	    }
	    }
    }

将Path路径下的oldname文件重命名为newname

/**
     * 将Path路径下的oldname文件重命名为newname
     * @param Path
     * @param oldname
     * @param newname 
     */
    public static void renameFile(String Path,String oldname,String newname){ 
        if(!oldname.equals(newname)){//新的文件名和以前文件名不同时,才有必要进行重命名 
            File oldfile=new File(Path+"/"+oldname); 
            File newfile=new File(Path+"/"+newname); 
            if(!oldfile.exists()){
                return;//重命名文件不存在
            }
            if(newfile.exists())//若在该目录下已经有一个文件和新文件名相同,则不允许重命名 
                System.out.println(newname+"已经存在!"); 
            else{ 
                oldfile.renameTo(newfile); 
            } 
        }else{
            System.out.println("新文件名和旧文件名相同...");
        }
    }

检查文件夹及其路径是否存在,否,则创建文件

 /**
     * 检查文件夹及其路径是否存在,否,则创建文件
     * @param FILEPATH
     * @param filename 
     */
     public static void checkFile(String FILEPATH,String filename) {
        File  file=new File(FILEPATH+filename);
		File fileDir= new File(FILEPATH);
		file=new File(FILEPATH+filename);
		if(!fileDir.exists()){
			fileDir.mkdirs();
		}
		if(!file.exists()){
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

判断身份证号是否符合格式

/**
      * 判断身份证号是否符合格式
      * @param idCard
      * @return 
      */
     public static boolean checkID(String idCard){
            //定义判别用户身份证号的正则表达式(要么是15位,要么是18位,最后一位可以为字母)  
            Pattern idNumPattern = Pattern.compile("(\\d{14}[0-9a-zA-Z])|(\\d{17}[0-9a-zA-Z])");  
            //通过Pattern获得Matcher  
            Matcher idNumMatcher = idNumPattern.matcher(idCard);  
            //判断用户输入是否为身份证号  
            if(idNumMatcher.matches()){  
                return true;
            }else{  
                //如果不符合,输出信息提示用户  
                return false; 
            }  
     }

比较两个日期,如果 DATE1 在 DATE2 之后则返回 true

/***
      * 比较两个日期,如果 DATE1 在 DATE2 之后则返回 true
      * @param DATE1
      * @param DATE2
      * @return 
      */
      public static boolean compare_date(String DATE1, String DATE2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date dt1 =df.parse(DATE1);
            Date dt2 =df.parse(DATE2);
            if (dt1.getTime() >= dt2.getTime()) {
               return true;
            } else if(dt1.getTime() < dt2.getTime()) {
               return false;
            }
       } catch (Exception exception) {
           exception.printStackTrace();
        }
        return false;
     }

猜你喜欢

转载自blog.csdn.net/vcx08/article/details/83750545