Java 程式設計中常用到的工具函式
阿新 • • 發佈:2019-01-01
在 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;
}