Android 工具类(历史最全持续更新)

Toast唯一

/**
 * toast 多次点击只会出现一个
 */
private static Toast toast;

public static void showToast(Context context,
                             String content) {
    if (toast == null) {
        toast = Toast.makeText(context,
                content,
                Toast.LENGTH_SHORT);
    } else {
        toast.setText(content);
    }
    toast.show();
}


检查网络是否连接

/**
 * 检查网络是否连通
 */
public static boolean isNetworkAvailable(Context context) {
    // 创建并初始化连接对象
    ConnectivityManager connMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    // 判断初始化是否成功并作出相应处理
    if (connMan != null) {
        // 调用getActiveNetworkInfo方法创建对象,如果不为空则表明网络连通,否则没连通
        NetworkInfo info = connMan.getActiveNetworkInfo();
        if (info != null) {
            return info.isAvailable();
        }
    }
    return false;
}

获取应用名称

/**
 * 获取应用程序名称
 */
public static String getAppName(Context context) {
    try {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo = packageManager.getPackageInfo(
                context.getPackageName(), 0);
        int labelRes = packageInfo.applicationInfo.labelRes;
        return context.getResources().getString(labelRes);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}


当前应用的版本code

/**
 *  当前应用的版本code,注意获取的是gradle里的code,gradle里没写的话在manifest里
 */
public static int getVersionCode(Context context) {
    try {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo = packageManager.getPackageInfo(
                context.getPackageName(),PackageManager.GET_ACTIVITIES);
        return packageInfo.versionCode ;

    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return 0;
}


当前应用的版本name

/**
 *  当前应用的版本名称,注意获取的是gradle里的code,gradle里没写的话在manifest里
 */
public static String getVersionName(Context context)
{
    try
    {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        return packageInfo.versionName;

    } catch (PackageManager.NameNotFoundException e)
    {
        e.printStackTrace();
    }
    return null;
}


检测手机号是否正确

/**
 *  检测手机号,返回boolean
 */
public static boolean checkPhone(String mobiles) {
    Pattern p = Pattern.compile("^((14[5,7])|(13[0-9])|(17[0-9])|(15[^4,\\D])|(18[0,1-9]))\\d{8}$");
    Matcher m = p.matcher(mobiles);
    return m.matches();
}


检测金额(保留后两位)

/**
 *  检测金额(保留小数点后两位)
 */
public static boolean checkMoney(String money) {
    Pattern p = Pattern.compile("^[0-9]+(.[0-9]{2})?$");
    Matcher m = p.matcher(money);
    return m.matches();
}

截取字符串,小数点后两位

/**
 * 截取字符串 小数点后两位,多删少补
 */
public static String formateRate(String rateStr) {
    if (rateStr.indexOf(".") != -1) {
        // 获取小数点的位置
        int num = 0;
        num = rateStr.indexOf(".");
        // 获取小数点后面的数字 是否有两位 不足两位补足两位
        String dianAfter = rateStr.substring(0, num + 1);
        String afterData = rateStr.replace(dianAfter, "");
        if (afterData.length() < 2) {
            afterData = afterData + "0";
        }
        return rateStr.substring(0, num) + "." + afterData.substring(0, 2);
    } else {
        return rateStr + ".00";

    }
}

MD5

/**
 * MD5
 */
    public final static String MD5(String s) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

线程休眠

/**
 * 线程休眠
 */
public class ThreadSleep {
    public static final long DEFAULT_SLEEP_TIME = 500;

    private boolean          isRuning           = false;

    public boolean isRuning() {
        return isRuning;
    }

    public void runWithTime(final long defaultSleepTime) {
        isRuning = true;
        new Thread() {

            @Override
            public void run() {
                try {
                    sleep(defaultSleepTime, 0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                isRuning = false;
                super.run();
            }
        }.start();
    }
}

异常类捕捉


/**
 * Created by ly on 2016/11/30.
 */

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * UncaughtException处理类,当程序发生Uncaught异常的时候,由该类来接管程序,并记录发送错误报告. 需要在Application中注册,为了要在程序启动器就监控整个程序。
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {
    /**
     * TAG
     */
    public static final String TAG = "CrashHandler";
    /**
     * 系统默认的UncaughtException处理类
     */
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    /**
     * CrashHandler实例
     */
    private static CrashHandler mCrashHandler;
    /**
     * 程序的Context对象
     */
    private Context mContext;
    /**
     * 用来存储设备信息和异常信息
     */
    private Map<String, String> infos = new HashMap<String, String>();
    /**
     * 用于格式化日期,作为日志文件名的一部分
     */
    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

    /**
     * 私有构造函数
     */
    private CrashHandler() {

    }

    /**
     * 获取CrashHandler实例 ,单例模式
     *
     * @return
     * @since V1.0
     */
    public static CrashHandler getInstance() {
        if (mCrashHandler == null)
            mCrashHandler = new CrashHandler();
        return mCrashHandler;
    }

    /**
     * 初始化
     *
     * @param context
     * @since V1.0
     */
    public void init(Context context) {
        mContext = context;
        // 获取系统默认的UncaughtException处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        // 设置该CrashHandler为程序的默认处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultHandler != null) {
            // 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                Log.e(TAG, "uncaughtException() InterruptedException:" + e);
            }
            // 退出程序
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false.
     * @since V1.0
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }

        // 收集设备参数信息
        collectDeviceInfo(mContext);

        // 使用Toast来显示异常信息
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出.", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        }.start();

        // 保存日志文件
//        saveCatchInfo2File(ex);
        restartApplication();
        return true;
    }

    /**
     * 收集设备参数信息
     *
     * @param ctx
     * @since V1.0
     */
    public void collectDeviceInfo(Context ctx) {
        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "null" : pi.versionName;
                String versionCode = pi.versionCode + "";
                infos.put("versionName", versionName);
                infos.put("versionCode", versionCode);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "collectDeviceInfo() an error occured when collect package info NameNotFoundException:", e);
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                infos.put(field.getName(), field.get(null).toString());
                Log.d(TAG, field.getName() + " : " + field.get(null));
            } catch (Exception e) {
                Log.e(TAG, "collectDeviceInfo() an error occured when collect crash info Exception:", e);
            }
        }
    }

    /**
     * 保存错误信息到文件中
     *
     * @param ex
     * @return 返回文件名称, 便于将文件传送到服务器
     */
    private String saveCatchInfo2File(Throwable ex) {
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : infos.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "\n");
        }

        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        sb.append(result);
        try {
            long timestamp = System.currentTimeMillis();
            String time = formatter.format(new Date());
            String fileName = "crash-" + time + "-" + timestamp + ".log";
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//                String path = FilePathUtil.getiVMSDirPath() + "/crash/";
                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/otm/";
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(path + fileName);
                fos.write(sb.toString().getBytes());
                // 发送给开发人员
                sendCrashLog2PM(path + fileName);
                fos.close();
            }
            return fileName;
        } catch (Exception e) {
            Log.e(TAG, "saveCatchInfo2File() an error occured while writing file... Exception:", e);
        }
        return null;
    }
    private void restartApplication() {
        final Intent intent = mContext.getPackageManager().getLaunchIntentForPackage(mContext.getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        mContext.startActivity(intent);
    }
    /**
     * 将捕获的导致崩溃的错误信息发送给开发人员 目前只将log日志保存在sdcard 和输出到LogCat中,并未发送给后台。
     *
     * @param fileName
     * @since V1.0
     */
    private void sendCrashLog2PM(String fileName) {
        if (!new File(fileName).exists()) {
            Log.e(TAG, "sendCrashLog2PM() 日志文件不存在");
            return;
        }
        FileInputStream fis = null;
        BufferedReader reader = null;
        String s = null;
        try {
            fis = new FileInputStream(fileName);
            reader = new BufferedReader(new InputStreamReader(fis, "GBK"));
            while (true) {
                s = reader.readLine();
                if (s == null)
                    break;
                // 由于目前尚未确定以何种方式发送,所以先打出log日志。
                Log.e(TAG, s);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally { // 关闭流
            try {
                reader.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


// 跳转到系统的网络设置界面  
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>  //所需权限
Intent intent = null;
// 先判断当前系统版本  
if(android.os.Build.VERSION.SDK_INT > 10){  // 3.0以上  
    intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
}else{
    intent = new Intent();
    intent.setClassName("com.android.settings", "com.android.settings.WirelessSettings");
}
context.startActivity(intent);


Intent wifiSettingsIntent = new Intent("android.settings.WIFI_SETTINGS");
startActivity(wifiSettingsIntent);

 手机号正则表达式


/**
 * 验证手机号码是否合法
 */
public static boolean validatePhoneNumber(String mobiles) {
        String telRegex = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(147,145))\\d{8}$";
        return !TextUtils.isEmpty(mobiles) && mobiles.matches(telRegex);
    
/**
 * 验证身份证号码是否合法
 */
public static boolean validateIDCardNumber(String number) {
        return (number.length() == 15 && number.matches("^\\d{15}"))
        || (number.length() == 18 && (number.matches("^\\d{17}[x,X,\\d]")));


/**
 * 验证工具类
 */
public class ValidateUtil {

    private static final int PASS_LOW_LIMIT = 6;
    private static final int PASS_HIGH_LIMIT = 16;

    /**
     * 验证手机号码是否合法
     */
    public static boolean validatePhoneNumber(String mobiles) {
        String telRegex = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(147,145))\\d{8}$";
        return !TextUtils.isEmpty(mobiles) && mobiles.matches(telRegex);
    }

    /**
     * 验证密码是否合法 6-16位
     */
    public static boolean validatePass(String password) {
        return password.length() >= PASS_LOW_LIMIT && password.length() <= PASS_HIGH_LIMIT;
    }


    /**
     * 验证身份证号码是否合法
     */
    public static boolean validateIDCardNumber(String number) {
        return (number.length() == 15 && number.matches("^\\d{15}"))
                || (number.length() == 18 && (number.matches("^\\d{17}[x,X,\\d]")));
    }


    /**
     * 判断是不是英文字母
     */
    public static boolean isECharacter(String codePoint) {
        return codePoint.matches("^[A-Za-z]$");
    }
}
/**
 * 判断应用是否已经启动
 *
 * @param context     上下文对象
 * @param packageName 要判断应用的包名
 * @return boolean
 */
        public static boolean isAppAlive(Context context, String packageName) {
            ActivityManager activityManager =
                    (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> processInfos
                    = activityManager.getRunningAppProcesses();
            for (int i = 0; i < processInfos.size(); i++) {
                if (processInfos.get(i).processName.equals(packageName)) {
                    return true;
                }
            }

            return false;
        }
/**
 * 判断服务是否正在运行
 *
 * @param serviceName 服务类的全路径名称 例如: com.jaychan.demo.service.PushService
 * @param context 上下文对象
 * @return
 */
        public static boolean isServiceRunning(String serviceName, Context context) {
            //活动管理器
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<RunningServiceInfo> runningServices = am.getRunningServices(100); //获取运行的服务,参数表示最多返回的数量

            for (RunningServiceInfo runningServiceInfo : runningServices) {
                String className = runningServiceInfo.service.getClassName();
                if (className.equals(serviceName)) {
                    return true; //判断服务是否运行
                }
            }

            return false;
        }
    /**
    * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
    */
   public static int dip2px(Context context, float dpValue) {
      final float scale = context.getResources().getDisplayMetrics().density;
      return (int) (dpValue * scale + 0.5f);
   }

   /**
    * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
    */
   public static int px2dip(Context context, float pxValue) {
      final float scale = context.getResources().getDisplayMetrics().density;
      return (int) (pxValue / scale + 0.5f);
   }

   /**
    * Md5 32位 or 16位 加密
    *
    * @param plainText
    * @return 32位加密
    */
   public static String Md5(String plainText) {
      StringBuffer buf = null;
      try {
         MessageDigest md = MessageDigest.getInstance("MD5");
         md.update(plainText.getBytes());
         byte b[] = md.digest();
         int i;
         buf = new StringBuffer("");
         for (int offset = 0; offset < b.length; offset++) {
            i = b[offset];
            if (i < 0) i += 256;
            if (i < 16)
               buf.append("0");
            buf.append(Integer.toHexString(i));
         }

      } catch (NoSuchAlgorithmException e) {
         e.printStackTrace();
      }
      return buf.toString();
   }

   /**
    * 手机号正则判断
    * @param str
    * @return
    * @throws PatternSyntaxException
    */
   public static boolean isPhoneNumber(String str) throws PatternSyntaxException {
      if (str != null) {
         String pattern = "(13\\d|14[579]|15[^4\\D]|17[^49\\D]|18\\d)\\d{8}";

         Pattern r = Pattern.compile(pattern);
         Matcher m = r.matcher(str);
         return m.matches();
      } else {
         return false;
      }
   }

   /**
    * 检测当前网络的类型 是否是wifi
    *
    * @param context
    * @return
    */
   public static int checkedNetWorkType(Context context) {
      if (!checkedNetWork(context)) {
         return 0;//无网络
      }
      ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting()) {
         return 1;//wifi
      } else {
         return 2;//非wifi
      }
   }

   /**
    * 检查是否连接网络
    *
    * @param context
    * @return
    */
   public static boolean checkedNetWork(Context context) {
      // 获得连接设备管理器
      ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (cm == null) return false;
      /**
       * 获取网络连接对象
       */
      NetworkInfo networkInfo = cm.getActiveNetworkInfo();

      if (networkInfo == null || !networkInfo.isAvailable()) {
         return false;
      }
      return true;
   }

   /**
    * 检测GPS是否打开
    *
    * @return
    */
   public static boolean checkGPSIsOpen(Context context) {
      boolean isOpen;
      LocationManager locationManager = (LocationManager) context
            .getSystemService(Context.LOCATION_SERVICE);
      if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)||locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
         isOpen=true;
      }else{
         isOpen = false;
      }

      return isOpen;
   }

   /**
    * 跳转GPS设置
    */
   public static void openGPSSettings(final Context context) {
      if (checkGPSIsOpen(context)) {
//            initLocation(); //自己写的定位方法
      } else {
//            //没有打开则弹出对话框
         AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.AlertDialogCustom);

         builder.setTitle("温馨提示");
         builder.setMessage("当前应用需要打开定位功能。请点击\"设置\"-\"定位服务\"打开定位功能。");
         //设置对话框是可取消的
         builder.setCancelable(false);

         builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
               dialogInterface.dismiss();
               //跳转GPS设置界面
               Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
               context.startActivity(intent);
            }
         });
         builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
               dialogInterface.dismiss();
               ActivityManager.getInstance().exit();
            }
         });
         AlertDialog alertDialog = builder.create();
         alertDialog.show();
      }
   }

   /**
    * 字符串进行Base64编码
    * @param str
    */
   public static String StringToBase64(String str){
      String encodedString = Base64.encodeToString(str.getBytes(), Base64.DEFAULT);
      return encodedString;
   }

   /**
    * 字符串进行Base64解码
    * @param encodedString
    * @return
    */
   public static String Base64ToString(String encodedString){
      String decodedString =new String(Base64.decode(encodedString,Base64.DEFAULT));
      return decodedString;
   }
   这里还有一个根据经纬度计算两点间真实距离的,一般都直接使用所集成第三方地图SDK中包含的方法,这里还是给出代码

   /**
    * 补充:计算两点之间真实距离
    *
    * @return     */
   public static double getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {
      // 维度
      double lat1 = (Math.PI / 180) * latitude1;
      double lat2 = (Math.PI / 180) * latitude2;

      // 经度
      double lon1 = (Math.PI / 180) * longitude1;
      double lon2 = (Math.PI / 180) * longitude2;

      // 地球半径
      double R = 6371;

      // 两点间距离 km,如果想要米的话,结果*1000就可以了
      double d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)) * R;

      return d * 1000;
   }
这里还有一个根据经纬度计算两点间真实距离的,一般都直接使用所集成第三方地图SDK中包含的方法,这里还是给出代码

/**
 * 补充:计算两点之间真实距离
 *
 * @return  */
public static double getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {
   // 维度
   double lat1 = (Math.PI / 180) * latitude1;
   double lat2 = (Math.PI / 180) * latitude2;

   // 经度
   double lon1 = (Math.PI / 180) * longitude1;
   double lon2 = (Math.PI / 180) * longitude2;

   // 地球半径
   double R = 6371;

   // 两点间距离 km,如果想要米的话,结果*1000就可以了
   double d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)) * R;

   return d * 1000;
}
常用文件类

文件类的代码较多,这里就只给出读写文件的

/**
 * 判断SD卡是否可用
 * @return SD卡可用返回true
 */
public static boolean hasSdcard() {
   String status = Environment.getExternalStorageState();
   return Environment.MEDIA_MOUNTED.equals(status);
}

/**
 * 读取文件的内容
 * <br>
 * 默认utf-8编码
 * @param filePath 文件路径
 * @return 字符串
 * @throws IOException
 */
public static String readFile(String filePath) throws IOException {
   return readFile(filePath, "utf-8");
}

/**
 * 读取文件的内容
 * @param filePath 文件目录
 * @param charsetName 字符编码
 * @return String字符串
 */
public static String readFile(String filePath, String charsetName)
      throws IOException {
   if (TextUtils.isEmpty(filePath))
      return null;
   if (TextUtils.isEmpty(charsetName))
      charsetName = "utf-8";
   File file = new File(filePath);
   StringBuilder fileContent = new StringBuilder("");
   if (file == null || !file.isFile())
      return null;
   BufferedReader reader = null;
   try {
      InputStreamReader is = new InputStreamReader(new FileInputStream(
            file), charsetName);
      reader = new BufferedReader(is);
      String line = null;
      while ((line = reader.readLine()) != null) {
         if (!fileContent.toString().equals("")) {
            fileContent.append("\r\n");
         }
         fileContent.append(line);
      }
      return fileContent.toString();
   } finally {
      if (reader != null) {
         try {
            reader.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }
   }
}

/**
 * 读取文本文件到List字符串集合中(默认utf-8编码)
 * @param filePath 文件目录
 * @return 文件不存在返回null,否则返回字符串集合
 * @throws IOException
 */
public static List<String> readFileToList(String filePath)
      throws IOException {
   return readFileToList(filePath, "utf-8");
}

/**
 * 读取文本文件到List字符串集合中
 * @param filePath 文件目录
 * @param charsetName 字符编码
 * @return 文件不存在返回null,否则返回字符串集合
 */
public static List<String> readFileToList(String filePath,
                                String charsetName) throws IOException {
   if (TextUtils.isEmpty(filePath))
      return null;
   if (TextUtils.isEmpty(charsetName))
      charsetName = "utf-8";
   File file = new File(filePath);
   List<String> fileContent = new ArrayList<String>();
   if (file == null || !file.isFile()) {
      return null;
   }
   BufferedReader reader = null;
   try {
      InputStreamReader is = new InputStreamReader(new FileInputStream(
            file), charsetName);
      reader = new BufferedReader(is);
      String line = null;
      while ((line = reader.readLine()) != null) {
         fileContent.add(line);
      }
      return fileContent;
   } finally {
      if (reader != null) {
         try {
            reader.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }
   }
}

/**
 * 向文件中写入数据
 * @param filePath 文件目录
 * @param content 要写入的内容
 * @param append 如果为 true,则将数据写入文件末尾处,而不是写入文件开始处
 * @return 写入成功返回true, 写入失败返回false
 * @throws IOException
 */
public static boolean writeFile(String filePath, String content,
                        boolean append) throws IOException {
   if (TextUtils.isEmpty(filePath))
      return false;
   if (TextUtils.isEmpty(content))
      return false;
   FileWriter fileWriter = null;
   try {
      createFile(filePath);
      fileWriter = new FileWriter(filePath, append);
      fileWriter.write(content);
      fileWriter.flush();
      return true;
   } finally {
      if (fileWriter != null) {
         try {
            fileWriter.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }
   }
}


/**
 * 向文件中写入数据<br>
 * 默认在文件开始处重新写入数据
 * @param filePath 文件目录
 * @param stream 字节输入流
 * @return 写入成功返回true,否则返回false
 * @throws IOException
 */
public static boolean writeFile(String filePath, InputStream stream)
      throws IOException {
   return writeFile(filePath, stream, false);
}

/**
 * 向文件中写入数据
 * @param filePath 文件目录
 * @param stream 字节输入流
 * @param append 如果为 true,则将数据写入文件末尾处;
 *              为false时,清空原来的数据,从头开始写
 * @return 写入成功返回true,否则返回false
 * @throws IOException
 */
public static boolean writeFile(String filePath, InputStream stream,
                        boolean append) throws IOException {
   if (TextUtils.isEmpty(filePath))
      throw new NullPointerException("filePath is Empty");
   if (stream == null)
      throw new NullPointerException("InputStream is null");
   return writeFile(new File(filePath), stream,
         append);
}

/**
 * 向文件中写入数据
 * 默认在文件开始处重新写入数据
 * @param file 指定文件
 * @param stream 字节输入流
 * @return 写入成功返回true,否则返回false
 * @throws IOException
 */
public static boolean writeFile(File file, InputStream stream)
      throws IOException {
   return writeFile(file, stream, false);
}

/**
 * 向文件中写入数据
 * @param file 指定文件
 * @param stream 字节输入流
 * @param append 为true时,在文件开始处重新写入数据;
 *              为false时,清空原来的数据,从头开始写
 * @return 写入成功返回true,否则返回false
 * @throws IOException
 */
public static boolean writeFile(File file, InputStream stream,
                        boolean append) throws IOException {
   if (file == null)
      throw new NullPointerException("file = null");
   OutputStream out = null;
   try {
      createFile(file.getAbsolutePath());
      out = new FileOutputStream(file, append);
      byte data[] = new byte[1024];
      int length = -1;
      while ((length = stream.read(data)) != -1) {
         out.write(data, 0, length);
      }
      out.flush();
      return true;
   } finally {
      if (out != null) {
         try {
            out.close();
            stream.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }
   }
}
日期工具类

      这个可是相当的常用啊

/**
 * 将long时间转成yyyy-MM-dd HH:mm:ss字符串<br>
 * @param timeInMillis 时间long值
 * @return yyyy-MM-dd HH:mm:ss
 */
public static String getDateTimeFromMillis(long timeInMillis) {
   return getDateTimeFormat(new Date(timeInMillis));
}

/**
 * 将date转成yyyy-MM-dd HH:mm:ss字符串
 * <br>
 * @param date Date对象
 * @return  yyyy-MM-dd HH:mm:ss
 */
public static String getDateTimeFormat(Date date) {
   return dateSimpleFormat(date, defaultDateTimeFormat.get());
}

/**
 * 将年月日的int转成yyyy-MM-dd的字符串
 * @param year  * @param month 月 1-12
 * @param day  * 注:月表示Calendar的月,比实际小1
 * 对输入项未做判断
 */
public static String getDateFormat(int year, int month, int day) {
   return getDateFormat(getDate(year, month, day));
}

/**
 * 获得HH:mm:ss的时间
 * @param date
 * @return
 */
public static String getTimeFormat(Date date) {
   return dateSimpleFormat(date, defaultTimeFormat.get());
}

/**
 * 格式化日期显示格式
 * @param sdate 原始日期格式 "yyyy-MM-dd"
 * @param format 格式化后日期格式
 * @return 格式化后的日期显示
 */
public static String dateFormat(String sdate, String format) {
   SimpleDateFormat formatter = new SimpleDateFormat(format);
   java.sql.Date date = java.sql.Date.valueOf(sdate);
   return dateSimpleFormat(date, formatter);
}

/**
 * 格式化日期显示格式
 * @param date Date对象
 * @param format 格式化后日期格式
 * @return 格式化后的日期显示
 */
public static String dateFormat(Date date, String format) {
   SimpleDateFormat formatter = new SimpleDateFormat(format);
   return dateSimpleFormat(date, formatter);
}
/**
 * 将date转成字符串
 * @param date Date
 * @param format SimpleDateFormat
 * <br>
 * 注: SimpleDateFormat为空时,采用默认的yyyy-MM-dd HH:mm:ss格式
 * @return yyyy-MM-dd HH:mm:ss
 */
public static String dateSimpleFormat(Date date, SimpleDateFormat format) {
   if (format == null)
      format = defaultDateTimeFormat.get();
   return (date == null ? "" : format.format(date));
}

/**
 * 将"yyyy-MM-dd HH:mm:ss" 格式的字符串转成Date
 * @param strDate 时间字符串
 * @return Date
 */
public static Date getDateByDateTimeFormat(String strDate) {
   return getDateByFormat(strDate, defaultDateTimeFormat.get());
}

/**
 * 将"yyyy-MM-dd" 格式的字符串转成Date
 * @param strDate
 * @return Date
 */
public static Date getDateByDateFormat(String strDate) {
   return getDateByFormat(strDate, defaultDateFormat.get());
}

/**
 * 将指定格式的时间字符串转成Date对象
 * @param strDate 时间字符串
 * @param format 格式化字符串
 * @return Date
 */
public static Date getDateByFormat(String strDate, String format) {
   return getDateByFormat(strDate, new SimpleDateFormat(format));
}

/**
 * 将String字符串按照一定格式转成Date<br>
 * 注: SimpleDateFormat为空时,采用默认的yyyy-MM-dd HH:mm:ss格式
 * @param strDate 时间字符串
 * @param format SimpleDateFormat对象
 * @exception ParseException 日期格式转换出错
 */
private static Date getDateByFormat(String strDate, SimpleDateFormat format) {
   if (format == null)
      format = defaultDateTimeFormat.get();
   try {
      return format.parse(strDate);
   } catch (ParseException e) {
      e.printStackTrace();
   }
   return null;
}

/**
 * 将年月日的int转成date
 * @param year  * @param month 月 1-12
 * @param day  * 注:月表示Calendar的月,比实际小1
 */
public static Date getDate(int year, int month, int day) {
   Calendar mCalendar = Calendar.getInstance();
   mCalendar.set(year, month - 1, day);
   return mCalendar.getTime();
}

/**
 * 求两个日期相差天数
 *
 * @param strat 起始日期,格式yyyy-MM-dd
 * @param end 终止日期,格式yyyy-MM-dd
 * @return 两个日期相差天数
 */
public static long getIntervalDays(String strat, String end) {
   return ((java.sql.Date.valueOf(end)).getTime() - (java.sql.Date
         .valueOf(strat)).getTime()) / (3600 * 24 * 1000);
}

/**
 * 获得当前年份
 * @return year(int)
 */
public static int getCurrentYear() {
   Calendar mCalendar = Calendar.getInstance();
   return mCalendar.get(Calendar.YEAR);
}

/**
 * 获得当前月份
 * @return month(int) 1-12
 */
public static int getCurrentMonth() {
   Calendar mCalendar = Calendar.getInstance();
   return mCalendar.get(Calendar.MONTH) + 1;
}

/**
 * 获得当月几号
 * @return day(int)
 */
public static int getDayOfMonth() {
   Calendar mCalendar = Calendar.getInstance();
   return mCalendar.get(Calendar.DAY_OF_MONTH);
}

/**
 * 获得今天的日期(格式:yyyy-MM-dd)
 * @return yyyy-MM-dd
 */
public static String getToday() {
   Calendar mCalendar = Calendar.getInstance();
   return getDateFormat(mCalendar.getTime());
}

/**
 * 获得昨天的日期(格式:yyyy-MM-dd)
 * @return yyyy-MM-dd
 */
public static String getYesterday() {
   Calendar mCalendar = Calendar.getInstance();
   mCalendar.add(Calendar.DATE, -1);
   return getDateFormat(mCalendar.getTime());
}

/**
 * 获得前天的日期(格式:yyyy-MM-dd)
 * @return yyyy-MM-dd
 */
public static String getBeforeYesterday() {
   Calendar mCalendar = Calendar.getInstance();
   mCalendar.add(Calendar.DATE, -2);
   return getDateFormat(mCalendar.getTime());
}

/**
 * 获得几天之前或者几天之后的日期
 * @param diff 差值:正的往后推,负的往前推
 * @return
 */
public static String getOtherDay(int diff) {
   Calendar mCalendar = Calendar.getInstance();
   mCalendar.add(Calendar.DATE, diff);
   return getDateFormat(mCalendar.getTime());
}

/**
 * 取得给定日期加上一定天数后的日期对象.
 *
 * @param //date 给定的日期对象
 * @param amount 需要添加的天数,如果是向前的天数,使用负数就可以.
 * @return Date 加上一定天数以后的Date对象.
 */
public static String getCalcDateFormat(String sDate, int amount) {
   Date date = getCalcDate(getDateByDateFormat(sDate), amount);
   return getDateFormat(date);
}

/**
 * 取得给定日期加上一定天数后的日期对象.
 *
 * @param date 给定的日期对象
 * @param amount 需要添加的天数,如果是向前的天数,使用负数就可以.
 * @return Date 加上一定天数以后的Date对象.
 */
public static Date getCalcDate(Date date, int amount) {
   Calendar cal = Calendar.getInstance();
   cal.setTime(date);
   cal.add(Calendar.DATE, amount);
   return cal.getTime();
}


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值