ToolUtils

直接上代码

package com.xxx.utils;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.ktc.base.SczwApplication;
import com.ktc.sczwdemo.R;

/**
 * @Date 2016-5-15 下午3:27:07
 * @Author Arvin
 * @Description 工具类
 */ 
public class ToolUtils {
    private static final String TAG = ToolUtils.class.getSimpleName();
    
    public static Context getContext() {
        return SczwApplication.getContext();
    }

    /**
     * 得到Resource对象
     */
    public static Resources getResources() {
        return getContext().getResources();
    }

    /**
     * @Description 获得应用的包名
     * @param null
     * @return String
     * @throws
     */
    public static String getPackageName() {
        return getContext().getPackageName();
    }
    
    /**
     * @Description 格式化空间大小
     * @param double
     * @return String
     * @throws
     */  
    public static String getFormatSize(double size) {  
        double kiloByte = size / 1024;  
        if (kiloByte < 1) {  
            return size + "B";  
        }  
  
        double megaByte = kiloByte / 1024;  
        if (megaByte < 1) {  
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));  
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)  
                    .toPlainString() + "KB";  
        }  
  
        double gigaByte = megaByte / 1024;  
        if (gigaByte < 1) {  
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));  
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)  
                    .toPlainString() + "MB";  
        }  
  
        double teraBytes = gigaByte / 1024;  
        if (teraBytes < 1) {  
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));  
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)  
                    .toPlainString() + "GB";  
        }  
        BigDecimal result4 = new BigDecimal(teraBytes);  
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()  
                + "TB";  
    }  
      
    /**
     * @Description 获取缓存空间cache大小
     * @param null
     * @return String
     * @throws Exception
     */  
    public static String getCacheSize() throws Exception {  
        return getFormatSize(getFolderSize(getContext().getExternalCacheDir()));  
    } 
    /**
     * @Description 获取cache路径空间大小
     * @param File
     * @return long
     * @throws Exception
     */ 
    public static long getFolderSize(File file) throws Exception {  
        long size = 0;  
        try {  
            File[] fileList = file.listFiles();  
            for (int i = 0; i < fileList.length; i++) {  
                if (fileList[i].isDirectory()) {  
                    size = size + getFolderSize(fileList[i]);  
                } else {  
                    size = size + fileList[i].length();  
                }  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return size;  
    }  
   
    /**
     * @Description 清除应用缓存,即删除data/data/packageName/cache目录下文件
     * @param null
     * @return null
     * @throws
     */
    public static void clearCache(){
        (new Thread(){
            @Override
            public void run() {
                try {
                    File path = getContext().getCacheDir();
                    if(path ==null)
                    return;
                    String killer =" rm -r " + path.toString();
                    Process p = Runtime.getRuntime().exec("su");
                    DataOutputStream os =new DataOutputStream(p.getOutputStream());
                    os.writeBytes(killer.toString() +"\n");
                    os.writeBytes("exit\n");
                    os.flush();
                } catch (IOException e) {
                    //TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();
    }
    
    /**
     * @Description 获取屏幕大小
     * @param null
     * @return int
     * @throws
     */
    public static Screen getScreenPix() {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(dm);
        return new Screen(dm.widthPixels, dm.heightPixels);
    }

    /**
     * @Description 获取屏幕宽度
     * @param null
     * @return int
     * @throws
     */
    public static int getScreenWidthPix() {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(dm);
        return new Screen(dm.widthPixels, dm.heightPixels).widthPixels;
    }

    /**
     * @Description 获取屏幕高度
     * @param null
     * @return int
     * @throws
     */
    public static int getScreenHeightPix() {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(dm);
        return new Screen(dm.widthPixels, dm.heightPixels).heightPixels;
    }
    
    /**
     * @Description 定义一个screen类型
     * @param tags
     * @return return_type
     * @throws
     */
    public static class Screen {
        public int widthPixels;
        public int heightPixels;

        public Screen() {
        }

        public Screen(int widthPixels, int heightPixels) {
            this.widthPixels = widthPixels;
            this.heightPixels = heightPixels;
        }

        @Override
        public String toString() {
            return "(" + widthPixels + "," + heightPixels + ")";
        }
    }
    
    /**
     * @Description 判断注册邮箱是否填写规范
     * @param String
     * @return boolean
     * @throws
     */
    public static boolean emailFormat(String email) {
        boolean tag = true;
        final String pattern1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        final Pattern pattern = Pattern.compile(pattern1);
        final Matcher mat = pattern.matcher(email);
        if (!mat.find()) {
            tag = false;
        }
        return tag;
    }

    /**
     * @Description 判断是否存在SDcard
     * @param null
     * @return boolean
     * @throws
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * @Description 定义Toast(string)
     * @param int
     * @return null
     * @throws
     */
    public static void showToast(String msg) {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }
    
    /**
     * @Description 定义Toast(id)
     * @param int
     * @return null
     * @throws
     */
    public static void showToast(int msg) {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }
    
    /**
     * @Description  验证字符串是否为空 或 ""
     * @param int
     * @return null
     * @throws
     */
    public static boolean validateString(String str) {
        if (str != null && !"".equals(str.trim()))
            return false;
        return true;
    }
    
    /**
     * @Description 获得渠道号(推广平台0=本站,1=安智,2=机锋,3=安卓官方)
     * @param null
     * @return String
     * @throws
     */
    public static String getChannelCode() {
        String channelCode = "0";
        try {
            ApplicationInfo ai = getContext().getPackageManager()
                    .getApplicationInfo(getContext().getPackageName(),
                            PackageManager.GET_META_DATA);
            Bundle bundle = ai.metaData;
            if (bundle != null) {

                Object obj = bundle.get("UMENG_CHANNEL");
                if (obj != null) {
                    channelCode = obj.toString();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return channelCode;
    }

    /**
     * @Description 检查网络是否可用
     * @param null
     * @return boolean
     * @throws
     */
    public static boolean isConnect() {
        // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
        try {
            ConnectivityManager connectivity = (ConnectivityManager) getContext()
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                // 获取网络连接管理的对象
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info != null && info.isConnected()) {
                    // 判断当前网络是否已经连接
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            Log.v("error", e.toString());
        }
        return false;
    }

    /**
     * @Description 对图片的大小进行判断,并得到合适的缩放比例,比如2即1/2,3即1/3
     * @param BitmapFactory.Options options,int minSideLength, int maxNumOfPixels
     * @return int
     * @throws
     */
    public static int computeSampleSize(BitmapFactory.Options options,
            int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength,
                maxNumOfPixels);

        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }
        return roundedSize;
    }

    private static int computeInitialSampleSize(BitmapFactory.Options options,
            int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;

        int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
                .sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 80 : (int) Math.min(
                Math.floor(w / minSideLength), Math.floor(h / minSideLength));

        if (upperBound < lowerBound) {
            // return the larger one when there is no overlapping zone.
            return lowerBound;
        }

        if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }
    
    /**
     * @Description MD5加密
     * @param String
     * @return String
     * @throws
     */
    public static String encryption(String enc) {
        String md5 = null;
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] bs = enc.getBytes();
            digest.update(bs);
            md5 = byte2hex(digest.digest());
            Log.i("md5", md5);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return md5;
    }

    private static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0xFF));
            if (stmp.length() == 1)
                hs = hs + "0" + stmp;
            else
                hs = hs + stmp;
        }
        return hs;
    }
    
    /**
     * @Description 以md5方式加密字符串
     * @param 默认32位长度
     * @return String
     * @throws
     */
    public static String getMd5() {
        try {
            String content = Constants.MD5_HEAD+getIMEI();
            MessageDigest bmd5 = MessageDigest.getInstance("MD5");
            bmd5.update(content.getBytes());
            int i;
            StringBuffer buf = new StringBuffer();
            byte[] b = bmd5.digest();
            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));
            }
            return buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
    
    /**
     * @Description 以md5方式加密字符串;返回的长度,支持16位和32位,例length=16,length=32
     * @param String
     * @return String
     * @throws
     */
    public static String getMd5(String content, int length) {
        try {
            MessageDigest bmd5 = MessageDigest.getInstance("MD5");
            bmd5.update(content.getBytes());
            int i;
            StringBuffer buf = new StringBuffer();
            byte[] b = bmd5.digest();
            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));
            }
            String md5Content = buf.toString();
            switch (length) {
            case 16:
                md5Content = md5Content.substring(0, 16);
                break;
            case 32:
            default:
                break;
            }
            return md5Content;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public ByteArrayOutputStream getByteArrayOutputStreamByInputStream(
            InputStream inputStream) throws Exception {

        byte[] buffer = new byte[1024];
        int len = -1;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, len);
        }
        return byteArrayOutputStream;
    }
    
    /**
     * @Description 切换白天和夜间模式
     * @param Window 当前的Window窗体;boolean是否是夜间模式
     * @return null
     * @throws
     */
    public void setScreenBrightness(Window window, boolean isNightModel) {
        WindowManager.LayoutParams lp = window.getAttributes();
        if (isNightModel) {
            lp.screenBrightness = 0.4f;
        } else {
            lp.screenBrightness = 1.0f;
        }
        window.setAttributes(lp);
    }
    
    /**
     * @Description 获取当前日期
     * @param null
     * @return String:2016-05-13
     * @throws
     */
    public static String getCurrentDate() {
        final Calendar c = Calendar.getInstance();
        int mYear = c.get(Calendar.YEAR); 
        int mMonth = c.get(Calendar.MONTH);
        int mDay = c.get(Calendar.DAY_OF_MONTH);
        return mYear + "-" + mMonth + "-" + mDay;
    }
    
    /**
     * @Description 获取6位随机数字
     * @param null
     * @return int
     * @throws
     */
    public static int getSixNum() {
        int numcode = (int) ((Math.random() * 9 + 1) * 100000);
        return numcode;
    }
    
    
    public static String getNumberFromString(String str) {
        String str2 = "";
        if (str != null && !"".equals(str)) {
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
                    str2 += str.charAt(i);
                }
            }
        }
        return str2;
    }

    /**
     * @Description 判断网络状态
     * @param null
     * @return boolean
     * @throws
     */
    public static boolean checkNet() {
        ConnectivityManager manager = (ConnectivityManager) getContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info != null) {
            return true;
        }
        return false;
    }

    public static String getAPN() {
        String apn = "";
        ConnectivityManager manager = (ConnectivityManager) getContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();

        if (info != null) {
            if (ConnectivityManager.TYPE_WIFI == info.getType()) {
                apn = info.getTypeName();
                if (apn == null) {
                    apn = "wifi";
                }
            } else {
                apn = info.getExtraInfo().toLowerCase();
                if (apn == null) {
                    apn = "mobile";
                }
            }
        }
        return apn;
    }

    public static String getModel() {
        return Build.MODEL;
    }

    public static String getManufacturer() {
        return Build.MANUFACTURER;
    }

    public static String getFirmware() {
        return Build.VERSION.RELEASE;
    }

    /**
     * @Description 获取设备SDK版本号
     * @param null
     * @return String
     * @throws
     */
    public static String getSDKVer() {
        return Integer.valueOf(Build.VERSION.SDK_INT).toString();
    }

    /**
     * @Description 获取当前语言类型
     * @param null
     * @return String
     * @throws
     */
    public static String getLanguage() {
        Locale locale = Locale.getDefault();
        String languageCode = locale.getLanguage();
        if (TextUtils.isEmpty(languageCode)) {
            languageCode = "";
        }
        return languageCode;
    }

    /**
     * @Description 获取当前国家码
     * @param null
     * @return String
     * @throws
     */
    public static String getCountry() {
        Locale locale = Locale.getDefault();
        String countryCode = locale.getCountry();
        if (TextUtils.isEmpty(countryCode)) {
            countryCode = "";
        }
        return countryCode;
    }

    /**
     * @Description 获取IMEI号码
     * @param null
     * @return String
     * @throws
     */
    public static String getIMEI() {
        TelephonyManager mTelephonyMgr = (TelephonyManager) getContext()
                .getSystemService(Context.TELEPHONY_SERVICE);
        String imei = mTelephonyMgr.getDeviceId();
        if (TextUtils.isEmpty(imei) || imei.equals("000000000000000")) {
            imei = "0";
        }

        return imei;
    }

    /**
     * @Description 获取到客户ID,即IMSI
     * @param null
     * @return String
     * @throws
     */
    public static String getIMSI() {
        TelephonyManager mTelephonyMgr = (TelephonyManager) getContext()
                .getSystemService(Context.TELEPHONY_SERVICE);
        String imsi = mTelephonyMgr.getSubscriberId();
        if (TextUtils.isEmpty(imsi)) {
            return "0";
        } else {
            return imsi;
        }
    }


    /**
     * @Description 获取本机手机号
     * @param null
     * @return String
     * @throws
     */
    public static String getLine1Number(){
        TelephonyManager telephonyManager=(TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
        String imei=telephonyManager.getLine1Number();
        return imei;
    }

    /**
     * @Description 获取网络运营商代号
     * @param null
     * @return String
     * @throws
     */
    public static String getMcnc() {

        TelephonyManager tm = (TelephonyManager) getContext()
                .getSystemService(Context.TELEPHONY_SERVICE);
        String mcnc = tm.getNetworkOperator();
        if (TextUtils.isEmpty(mcnc)) {
            return "0";
        } else {
            return mcnc;
        }
    }

    /**
     * @Description 获取手机的sdk版本号
     * @param null
     * @return int
     * @throws
     */
    public static int getPhoneSDK() {
        TelephonyManager phoneMgr = (TelephonyManager) getContext()
                .getSystemService(Context.TELEPHONY_SERVICE);
        Logger.i(TAG, "Bild model:" + Build.MODEL);
        Logger.i(TAG, "Phone Number:" + phoneMgr.getLine1Number());
        Logger.i(TAG, "SDK VERSION:" + Build.VERSION.SDK);
        Logger.i(TAG, "SDK RELEASE:" + Build.VERSION.RELEASE);
        int sdk = 7;
        try {
            sdk = Integer.parseInt(Build.VERSION.SDK);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return sdk;
    }

    public static Object getMetaData(String keyName) {
        try {
            ApplicationInfo info = getContext().getPackageManager()
                    .getApplicationInfo(getContext().getPackageName(),
                            PackageManager.GET_META_DATA);

            Bundle bundle = info.metaData;
            Object value = bundle.get(keyName);
            return value;
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @Description 获取应用版本信息
     * @param null
     * @return String
     * @throws
     */
    public static String getAppVersion() {
        PackageManager pm = getContext().getPackageManager();
        PackageInfo pi;
        try {
            pi = pm.getPackageInfo(getContext().getPackageName(), 0);
            String versionName = pi.versionName;
            return versionName;
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 判断SDCard是否已满
     * 
     * @return
     */
    public static boolean isSDCardSizeOverflow() {
        boolean result = false;
        // 取得SDCard当前的状态
        String sDcString = android.os.Environment.getExternalStorageState();

        if (sDcString.equals(android.os.Environment.MEDIA_MOUNTED)) {

            // 取得sdcard文件路径
            File pathFile = android.os.Environment
                    .getExternalStorageDirectory();
            android.os.StatFs statfs = new android.os.StatFs(pathFile.getPath());

            // 获取SDCard上BLOCK总数
            long nTotalBlocks = statfs.getBlockCount();

            // 获取SDCard上每个block的SIZE
            long nBlocSize = statfs.getBlockSize();

            // 获取可供程序使用的Block的数量
            long nAvailaBlock = statfs.getAvailableBlocks();

            // 获取剩下的所有Block的数量(包括预留的一般程序无法使用的块)
            long nFreeBlock = statfs.getFreeBlocks();

            // 计算SDCard 总容量大小MB
            long nSDTotalSize = nTotalBlocks * nBlocSize / 1024 / 1024;

            // 计算 SDCard 剩余大小MB
            long nSDFreeSize = nAvailaBlock * nBlocSize / 1024 / 1024;
            if (nSDFreeSize <= 1) {
                result = true;
            }
        }// end of if
            // end of func
        return result;
    }
    
    /**
     * @Description 格式化时间
     * @param Long
     * @return String
     * @throws
     */
   public static String getFomatTime(Long time){
        SimpleDateFormat format=new SimpleDateFormat(ResUtils.getString(R.string.time_format));  
        Date date = new Date(time);  
        String time_str = format.format(date);
        return time_str; 
   }
    
   
   /**
 * @Description 判断字符串是否是邮箱格式
 * @param String
 * @return Boolean
 * @throws
 */
    public static boolean checkEmail(String str) {
        Boolean isEmail = false;
        String expr = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        if (str.matches(expr)) {
            isEmail = true;
        }
        return isEmail;
    }

     /**
     * @Description 判断字符串是否是银行卡号
     * @param String
     * @return Boolean
     * @throws
     */
  public static boolean checkBankCard(String cardId) {  
      char bit = getBankCardCheckCode(cardId  
              .substring(0, cardId.length() - 1));  
      if (bit == 'N') {  
          return false;  
      }  
      return cardId.charAt(cardId.length() - 1) == bit;  

  }  
  
  private static char getBankCardCheckCode(String nonCheckCodeCardId) {  
      if (nonCheckCodeCardId == null  
              || nonCheckCodeCardId.trim().length() == 0  
              || !nonCheckCodeCardId.matches("\\d+")) {  
          // 如果传的不是数据返回N  
          return 'N';  
      }  
      char[] chs = nonCheckCodeCardId.trim().toCharArray();  
      int luhmSum = 0;  
      for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {  
          int k = chs[i] - '0';  
          if (j % 2 == 0) {  
              k *= 2;  
              k = k / 10 + k % 10;  
          }  
          luhmSum += k;  
      }  
      return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');  
  }

  /**
   * @Description 判断字符串是否是手机号
   * @param String
   * @return Boolean
   * @throws
   */
  public static boolean checkPhone(String phone) {  
      Pattern pattern = Pattern  
              .compile("^(13[0-9]|15[0-9]|153|15[6-9]|180|18[23]|18[5-9])\\d{8}$");  
      Matcher matcher = pattern.matcher(phone);  

      if (matcher.matches()) {  
          return true;  
      }  
      return false;  
  }
  
  /**
 * @Description 在指定文件夹中创建文件
 * @param tags
 * @return return_type
 * @throws
 */
   public static void makeNewFile(String filePath){
       if(hasSdcard()&&!isSDCardSizeOverflow()){
             File sdcardDir =Environment.getExternalStorageDirectory();
             String rootPath = sdcardDir.getPath()+"/SCZW";
             File file = new File(rootPath);
            if (!file.exists()) {
                 file.mkdirs();
            }
            //创建文件
            File newFile = new File(rootPath+"/"+filePath);
            if (!newFile.exists()) {
                try {
                    newFile.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
           }
      }
  }
   
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,444评论 4 365
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,867评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,157评论 0 248
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,312评论 0 214
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,673评论 3 289
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,802评论 1 223
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,010评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,743评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,470评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,696评论 2 250
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,187评论 1 262
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,538评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,188评论 3 240
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,127评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,902评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,889评论 2 283
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,741评论 2 274

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,582评论 25 707
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,214评论 0 17
  • 我们想要活出自己,就必须得走出围栏。这是我看完《橙沙之味》这部电影最深的感触。 影片一开始就是千太郎的满面愁容,无...
    吃火锅吗阅读 274评论 0 0
  • 今天风和日丽,天气正好,我终于身临其境的感受了一下落地窗外差异化的风光,似乎来到了市区的城乡结合部,顿时百感交集!...
    吾泪阅读 370评论 0 0