移动:134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、178、182、183、184、187、188
93 | *联通:130、131、132、145、155、156、175、176、185、186
94 | *电信:133、153、173、177、180、181、189
95 | *全球星:1349
96 | *虚拟运营商:170
97 | */ 98 | public static final String REGEX_MOBILE_EXACT = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|(147))\\d{8}$"; 99 | /** 100 | * 正则:电话号码 101 | */ 102 | public static final String REGEX_TEL = "^0\\d{2,3}[- ]?\\d{7,8}"; 103 | /** 104 | * 正则:身份证号码15位 105 | */ 106 | public static final String REGEX_IDCARD15 = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$"; 107 | /** 108 | * 正则:身份证号码18位 109 | */ 110 | public static final String REGEX_IDCARD18 = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9Xx])$"; 111 | /** 112 | * 正则:邮箱 113 | */ 114 | public static final String REGEX_EMAIL = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"; 115 | /** 116 | * 正则:URL 117 | */ 118 | public static final String REGEX_URL = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?"; 119 | /** 120 | * 正则:汉字 121 | */ 122 | public static final String REGEX_CHZ = "^[\\u4e00-\\u9fa5]+$"; 123 | /** 124 | * 正则:用户名,取值范围为a-z,A-Z,0-9,"_",汉字,不能以"_"结尾,用户名必须是6-20位 125 | */ 126 | public static final String REGEX_USERNAME = "^[\\w\\u4e00-\\u9fa5]{6,20}(? 255) { 123 | brightness = screenBrightness % 255; 124 | if (brightness == 0) { 125 | brightness = 255; 126 | } 127 | } 128 | boolean result = Settings.System.putInt(context.getContentResolver(), 129 | Settings.System.SCREEN_BRIGHTNESS, brightness); 130 | return result; 131 | } 132 | 133 | /** 134 | * Set window brightness, cannot change system brightness. 135 | * 设置窗口亮度,不能改变系统亮度 136 | * 137 | * @param activity 138 | * @param screenBrightness 0-255 139 | */ 140 | public static void setWindowBrightness(Activity activity, 141 | float screenBrightness) { 142 | float brightness = screenBrightness; 143 | if (screenBrightness < 1) { 144 | brightness = 1; 145 | } else if (screenBrightness > 255) { 146 | brightness = screenBrightness % 255; 147 | if (brightness == 0) { 148 | brightness = 255; 149 | } 150 | } 151 | Window window = activity.getWindow(); 152 | WindowManager.LayoutParams localLayoutParams = window.getAttributes(); 153 | localLayoutParams.screenBrightness = brightness / 255.0f; 154 | window.setAttributes(localLayoutParams); 155 | } 156 | 157 | /** 158 | * Set screen brightness and change system brightness, must declare the 159 | * 设置屏幕亮度并改变系统亮度,必须声明 160 | * {@link Manifest.permission#WRITE_SETTINGS} permission in its manifest. 161 | * 162 | * @param activity 163 | * @param screenBrightness 0-255 164 | * @return 165 | */ 166 | public static boolean setScreenBrightnessAndApply(Activity activity, 167 | int screenBrightness) { 168 | boolean result = setScreenBrightness(activity, screenBrightness); 169 | if (result) { 170 | setWindowBrightness(activity, screenBrightness); 171 | } 172 | return result; 173 | } 174 | 175 | /** 176 | * Get screen dormant time, must declare the 177 | * 获得屏幕休眠时间,必须声明 178 | * {@link Manifest.permission#WRITE_SETTINGS} permission in its manifest. 179 | * 180 | * @param context 181 | * @return dormantTime:ms, default:30s 182 | */ 183 | public static int getScreenDormantTime(Context context) { 184 | return Settings.System.getInt(context.getContentResolver(), 185 | Settings.System.SCREEN_OFF_TIMEOUT, 30000); 186 | } 187 | 188 | /** 189 | * Set screen dormant time by millis, must declare the 190 | * 屏幕休眠时间等信息,必须申报 191 | * {@link Manifest.permission#WRITE_SETTINGS} permission in its manifest. 192 | * 193 | * @param context 194 | * @return 195 | */ 196 | public static boolean setScreenDormantTime(Context context, int millis) { 197 | return Settings.System.putInt(context.getContentResolver(), 198 | Settings.System.SCREEN_OFF_TIMEOUT, millis); 199 | } 200 | 201 | /** 202 | * Get airplane mode, must declare the 203 | * 获取飞行模式,必须申报 204 | * {@link Manifest.permission#WRITE_APN_SETTINGS} permission in its manifest. 205 | * 206 | * @param context 207 | * @return 1:open, 0:close, default:close 208 | */ 209 | public static int getAirplaneMode(Context context) { 210 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { 211 | return Settings.System.getInt(context.getContentResolver(), 212 | Settings.System.AIRPLANE_MODE_ON, 0); 213 | } else { 214 | return Settings.Global.getInt(context.getContentResolver(), 215 | Settings.Global.AIRPLANE_MODE_ON, 0); 216 | } 217 | } 218 | 219 | /** 220 | * Judge whether airplane is open, must declare the 221 | * 判断飞行模式是否打开,必须声明 222 | * {@link Manifest.permission#WRITE_APN_SETTINGS} permission in its manifest. 223 | * 224 | * @param context 225 | * @return true:open, false:close, default:close 226 | */ 227 | public static boolean isAirplaneModeOpen(Context context) { 228 | return getAirplaneMode(context) == 1; 229 | } 230 | 231 | /** 232 | * Set airplane mode, must declare the 233 | * 设置飞行模式,必须声明 234 | * {@link Manifest.permission#WRITE_APN_SETTINGS} permission in its manifest. 235 | * 236 | * @param context 237 | * @param enable 238 | * @return 239 | */ 240 | public static boolean setAirplaneMode(Context context, boolean enable) { 241 | boolean result = true; 242 | if (isAirplaneModeOpen(context) != enable) { 243 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { 244 | result = Settings.System.putInt(context.getContentResolver(), 245 | Settings.System.AIRPLANE_MODE_ON, enable ? 1 : 0); 246 | } else { 247 | result = Settings.Global.putInt(context.getContentResolver(), 248 | Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0); 249 | } 250 | context.sendBroadcast(new Intent( 251 | Intent.ACTION_AIRPLANE_MODE_CHANGED)); 252 | } 253 | return result; 254 | } 255 | 256 | /** 257 | * Get bluetooth state 258 | * 获取蓝牙状态 259 | * 260 | * @return STATE_OFF, STATE_TURNING_OFF, STATE_ON, STATE_TURNING_ON, NONE 261 | * @throws Exception 262 | */ 263 | @RequiresPermission(Manifest.permission.BLUETOOTH) 264 | public static Integer getBluetoothState() { 265 | BluetoothAdapter bluetoothAdapter = BluetoothAdapter 266 | .getDefaultAdapter(); 267 | if (bluetoothAdapter == null) { 268 | return null; 269 | } else { 270 | return bluetoothAdapter.getState(); 271 | } 272 | } 273 | 274 | /** 275 | * Judge bluetooth is open 276 | * 判断蓝牙是否打开 277 | * 278 | * @return true:open, false:close. 279 | */ 280 | public static boolean isBluetoothOpen() { 281 | @SuppressLint("MissingPermission") Integer bluetoothStateCode = getBluetoothState(); 282 | if (bluetoothStateCode == null) { 283 | return false; 284 | } 285 | return bluetoothStateCode == BluetoothAdapter.STATE_ON 286 | || bluetoothStateCode == BluetoothAdapter.STATE_TURNING_ON; 287 | } 288 | 289 | /** 290 | * Set bluetooth 291 | * 设置蓝牙 292 | * 293 | * @param enable 294 | */ 295 | @RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN) 296 | public static void setBluetooth(boolean enable) throws Exception { 297 | if (isBluetoothOpen() != enable) { 298 | if (enable) { 299 | BluetoothAdapter.getDefaultAdapter().enable(); 300 | } else { 301 | BluetoothAdapter.getDefaultAdapter().disable(); 302 | } 303 | } 304 | } 305 | 306 | /** 307 | * Get media volume 308 | * 获取音量 309 | * 310 | * @param context 311 | * @return volume:0-15 312 | */ 313 | public static int getMediaVolume(Context context) { 314 | return ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).getStreamVolume(AudioManager 315 | .STREAM_MUSIC); 316 | } 317 | 318 | /** 319 | * Set media volume 320 | *设置音量 321 | * 322 | * @param context 323 | * @return volume:0-15 324 | */ 325 | public static void setMediaVolume(Context context, int mediaVloume) { 326 | if (mediaVloume < 0) { 327 | mediaVloume = 0; 328 | } else if (mediaVloume > 15) { 329 | mediaVloume = mediaVloume % 15; 330 | if (mediaVloume == 0) { 331 | mediaVloume = 15; 332 | } 333 | } 334 | ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).setStreamVolume(AudioManager.STREAM_MUSIC, 335 | mediaVloume, AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI); 336 | } 337 | 338 | /** 339 | * Get ring volume 340 | * 获取铃声音量 341 | * 342 | * @param context 343 | * @return volume:0-7 344 | */ 345 | public static int getRingVolume(Context context) { 346 | return ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).getStreamVolume(AudioManager 347 | .STREAM_RING); 348 | } 349 | 350 | /** 351 | * Set ring volume 352 | * 设置铃声音量 353 | * 354 | * @param context 355 | * @return volume:0-7 356 | */ 357 | public static void setRingVolume(Context context, int ringVloume) { 358 | if (ringVloume < 0) { 359 | ringVloume = 0; 360 | } else if (ringVloume > 7) { 361 | ringVloume = ringVloume % 7; 362 | if (ringVloume == 0) { 363 | ringVloume = 7; 364 | } 365 | } 366 | ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).setStreamVolume(AudioManager.STREAM_RING, 367 | ringVloume, AudioManager.FLAG_PLAY_SOUND); 368 | } 369 | } 370 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/DisplayUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.app.Activity; 5 | import android.content.Context; 6 | import android.content.res.Configuration; 7 | import android.graphics.Rect; 8 | import android.util.DisplayMetrics; 9 | import android.view.Window; 10 | 11 | /** 12 | * @author wlj 13 | * @date 2017/3/29 14 | * @email wanglijundev@gmail.com 15 | * @packagename wanglijun.vip.androidutils.utils 16 | * @desc: 屏幕相关 17 | */ 18 | 19 | public class DisplayUtils { 20 | /** 21 | * 是否横屏 22 | * 23 | * @param context 24 | * @return 25 | */ 26 | public static boolean isLandscape(Context context) { 27 | return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; 28 | } 29 | 30 | /** 31 | * 是否竖屏 32 | * 33 | * @param context 34 | * @return 35 | */ 36 | public static boolean isPortrait(Context context) { 37 | return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT; 38 | } 39 | 40 | /** 41 | * Get screen width, in pixels 42 | * 43 | * @param context 44 | * @return 45 | */ 46 | public static int getScreenWidth(Context context) { 47 | DisplayMetrics dm = context.getResources().getDisplayMetrics(); 48 | return dm.widthPixels; 49 | } 50 | 51 | /** 52 | * Get screen height, in pixels 53 | * 54 | * @param context 55 | * @return 56 | */ 57 | public static int getScreenHeight(Context context) { 58 | DisplayMetrics dm = context.getResources().getDisplayMetrics(); 59 | return dm.heightPixels; 60 | } 61 | 62 | /** 63 | * Get screen density, the logical density of the display 64 | * 65 | * @param context 66 | * @return 67 | */ 68 | public static float getScreenDensity(Context context) { 69 | DisplayMetrics dm = context.getResources().getDisplayMetrics(); 70 | return dm.density; 71 | } 72 | 73 | /** 74 | * Get screen density dpi, the screen density expressed as dots-per-inch 75 | * 76 | * @param context 77 | * @return 78 | */ 79 | public static int getScreenDensityDPI(Context context) { 80 | DisplayMetrics dm = context.getResources().getDisplayMetrics(); 81 | return dm.densityDpi; 82 | } 83 | 84 | /** 85 | * Get titleBar height, this method cannot be used in onCreate(),onStart(),onResume(), unless it is called in the 86 | * post(Runnable). 87 | * 88 | * @param activity 89 | * @return 90 | */ 91 | public static int getTitleBarHeight(Activity activity) { 92 | int statusBarHeight = getStatusBarHeight(activity); 93 | int contentViewTop = activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); 94 | int titleBarHeight = contentViewTop - statusBarHeight; 95 | return titleBarHeight < 0 ? 0 : titleBarHeight; 96 | } 97 | 98 | /** 99 | * Get statusbar height, this method cannot be used in onCreate(),onStart(),onResume(), unless it is called in the 100 | * post(Runnable). 101 | * 102 | * @param activity 103 | * @return 104 | */ 105 | public static int getStatusBarHeight(Activity activity) { 106 | Rect rect = new Rect(); 107 | activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect); 108 | return rect.top; 109 | } 110 | 111 | /** 112 | * Get statusBar height 113 | * 114 | * @param activity 115 | * @return 116 | */ 117 | @SuppressLint("PrivateApi") 118 | public static int getStatusBarHeight2(Activity activity) { 119 | int statusBarHeight = getStatusBarHeight(activity); 120 | if (0 == statusBarHeight) { 121 | Class> localClass; 122 | try { 123 | localClass = Class.forName("com.android.internal.R$dimen"); 124 | Object localObject = localClass.newInstance(); 125 | int id = Integer.parseInt(localClass.getField("status_bar_height").get(localObject).toString()); 126 | statusBarHeight = activity.getResources().getDimensionPixelSize(id); 127 | } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | IllegalArgumentException | SecurityException | NoSuchFieldException e) { 128 | e.printStackTrace(); 129 | } 130 | } 131 | return statusBarHeight; 132 | } 133 | 134 | /** 135 | * Convert dp to px by the density of phone 136 | * 137 | * @param context 138 | * @param dp 139 | * @return 140 | */ 141 | public static int dip2px(Context context, float dp) { 142 | if (context == null) { 143 | return -1; 144 | } 145 | return (int) (dipToPx(context, dp) + 0.5f); 146 | } 147 | 148 | /** 149 | * Convert dp to px 150 | * 151 | * @param context 152 | * @param dp 153 | * @return 154 | */ 155 | private static float dipToPx(Context context, float dp) { 156 | if (context == null) { 157 | return -1; 158 | } 159 | float scale = context.getResources().getDisplayMetrics().density; 160 | return dp * scale; 161 | } 162 | 163 | /** 164 | * Convert px to dp by the density of phone 165 | * 166 | * @param context 167 | * @param px 168 | * @return 169 | */ 170 | public static int px2dip(Context context, float px) { 171 | if (context == null) { 172 | return -1; 173 | } 174 | return (int) (pxToDip(context, px) + 0.5f); 175 | } 176 | 177 | /** 178 | * Convert px to dp 179 | * 180 | * @param context 181 | * @param px 182 | * @return 183 | */ 184 | private static float pxToDip(Context context, float px) { 185 | if (context == null) { 186 | return -1; 187 | } 188 | float scale = context.getResources().getDisplayMetrics().density; 189 | return px / scale; 190 | } 191 | 192 | /** 193 | * Convert px to sp 194 | * 195 | * @param context 196 | * @param px 197 | * @return 198 | */ 199 | public static int px2sp(Context context, float px) { 200 | return (int) (pxToSp(context, px) + 0.5f); 201 | } 202 | 203 | /** 204 | * Convert px to sp 205 | * 206 | * @param context 207 | * @param px 208 | * @return 209 | */ 210 | private static float pxToSp(Context context, float px) { 211 | float fontScale = context.getResources().getDisplayMetrics().scaledDensity; 212 | return px / fontScale; 213 | } 214 | 215 | /** 216 | * Convert sp to px 217 | * 218 | * @param context 219 | * @param sp 220 | * @return 221 | */ 222 | public static int sp2px(Context context, float sp) { 223 | return (int) (spToPx(context, sp) + 0.5f); 224 | } 225 | 226 | /** 227 | * Convert sp to px 228 | * 229 | * @param context 230 | * @param sp 231 | * @return 232 | */ 233 | private static float spToPx(Context context, float sp) { 234 | float fontScale = context.getResources().getDisplayMetrics().scaledDensity; 235 | return sp * fontScale; 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/FileLog.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import android.util.Log; 4 | 5 | import java.io.BufferedWriter; 6 | import java.io.File; 7 | import java.io.FileWriter; 8 | import java.io.IOException; 9 | import java.text.SimpleDateFormat; 10 | import java.util.Calendar; 11 | import java.util.Date; 12 | 13 | 14 | /** 15 | * @author wlj 16 | * @date 2017/3/28 17 | * @email wanglijundev@gmail.com 18 | * @packagename wanglijun.vip.androidutils 19 | * @description 带日志文件输入的,又可控开关的日志调试 20 | */ 21 | public class FileLog { 22 | 23 | /** 24 | * 日志文件总开关 25 | */ 26 | private static Boolean MYLOG_SWITCH = false; 27 | /** 28 | * 日志写入文件开关 29 | */ 30 | private static Boolean MYLOG_WRITE_TO_FILE = false; 31 | /** 32 | * 输入日志类型,w代表只输出告警信息等,v代表输出所有信息 33 | */ 34 | private static char MYLOG_TYPE = 'v'; 35 | /** 36 | * sd卡中日志文件的最多保存天数 37 | */ 38 | private static int SDCARD_LOG_FILE_SAVE_DAYS = 0; 39 | /** 40 | * 目录 41 | */ 42 | private static String sDirs; 43 | /** 44 | * 本类输出的日志文件名称 45 | */ 46 | private static String MYLOGFILEName = "Log.txt"; 47 | /** 48 | * 日志的输出格式 49 | */ 50 | private static SimpleDateFormat myLogSdf = new SimpleDateFormat( 51 | "yyyy-MM-dd HH:mm:ss"); 52 | /** 53 | * 日志文件格式 54 | */ 55 | private static SimpleDateFormat logfile = new SimpleDateFormat("yyyy-MM-dd"); 56 | 57 | public static void w(String tag, Object msg) { // 警告信息 58 | log(tag, msg.toString(), 'w'); 59 | } 60 | 61 | public static void e(String tag, Object msg) { // 错误信息 62 | log(tag, msg.toString(), 'e'); 63 | } 64 | 65 | public static void d(String tag, Object msg) {// 调试信息 66 | log(tag, msg.toString(), 'd'); 67 | } 68 | 69 | public static void i(String tag, Object msg) {// 70 | log(tag, msg.toString(), 'i'); 71 | } 72 | 73 | public static void v(String tag, Object msg) { 74 | log(tag, msg.toString(), 'v'); 75 | } 76 | 77 | public static void w(String tag, String text) { 78 | log(tag, text, 'w'); 79 | } 80 | 81 | public static void e(String tag, String text) { 82 | log(tag, text, 'e'); 83 | } 84 | 85 | public static void d(String tag, String text) { 86 | log(tag, text, 'd'); 87 | } 88 | 89 | public static void i(String tag, String text) { 90 | log(tag, text, 'i'); 91 | } 92 | 93 | public static void v(String tag, String text) { 94 | log(tag, text, 'v'); 95 | } 96 | 97 | /** 98 | * 配置文件log 99 | * 100 | * @param dirs 目录 101 | * @param isShowLog true表示写入 102 | */ 103 | public static void setConfig(String dirs, boolean isShowLog) { 104 | sDirs = dirs; 105 | MYLOG_SWITCH = isShowLog; 106 | MYLOG_WRITE_TO_FILE = isShowLog; 107 | } 108 | 109 | /** 110 | * 根据tag, msg和等级,输出日志 111 | * 112 | * @param tag 113 | * @param msg 114 | * @param level 115 | * @return void 116 | * @since v 1.0 117 | */ 118 | private static void log(String tag, String msg, char level) { 119 | if (MYLOG_SWITCH) { 120 | if ('e' == level && ('e' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) { 121 | Log.e(tag, msg); 122 | } else if ('w' == level && ('w' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) { 123 | Log.w(tag, msg); 124 | } else if ('d' == level && ('d' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) { 125 | Log.d(tag, msg); 126 | } else if ('i' == level && ('d' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) { 127 | Log.i(tag, msg); 128 | } else { 129 | Log.v(tag, msg); 130 | 131 | } 132 | if (MYLOG_WRITE_TO_FILE) { 133 | writeLogToFile(String.valueOf(level), tag, msg); 134 | } 135 | } 136 | } 137 | 138 | /** 139 | * 打开日志文件并写入日志 140 | * 新建或打开日志文件 141 | * @return 142 | **/ 143 | private static void writeLogToFile(String myLogType, String tag, String text) { 144 | Date newTime = new Date(); 145 | String needWriteFile = logfile.format(newTime); 146 | String needWriteMessage = myLogSdf.format(newTime) + " " + myLogType 147 | + " " + tag + " " + text; 148 | File dir = new File(sDirs); 149 | if (!dir.exists()) { 150 | dir.mkdirs(); 151 | } 152 | File file = new File(sDirs, needWriteFile 153 | + MYLOGFILEName); 154 | try { 155 | //后面这个参数代表是不是要接上文件中原来的数据,不进行覆盖 156 | FileWriter filerWriter = new FileWriter(file, true); 157 | BufferedWriter bufWriter = new BufferedWriter(filerWriter); 158 | bufWriter.write(needWriteMessage); 159 | bufWriter.newLine(); 160 | bufWriter.close(); 161 | filerWriter.close(); 162 | } catch (IOException e) { 163 | e.printStackTrace(); 164 | } 165 | } 166 | 167 | /** 168 | * 删除制定的日志文件 169 | */ 170 | public static void delFile() {// 删除日志文件 171 | String needDelFile = logfile.format(getDateBefore()); 172 | File file = new File(sDirs, needDelFile + MYLOGFILEName); 173 | if (file.exists()) { 174 | file.delete(); 175 | } 176 | } 177 | 178 | /** 179 | * 得到现在时间前的几天日期,用来得到需要删除的日志文件名 180 | */ 181 | private static Date getDateBefore() { 182 | Date newTime = new Date(); 183 | Calendar now = Calendar.getInstance(); 184 | now.setTime(newTime); 185 | now.set(Calendar.DATE, now.get(Calendar.DATE) 186 | - SDCARD_LOG_FILE_SAVE_DAYS); 187 | return now.getTime(); 188 | } 189 | 190 | } -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/FileSize.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 北京博瑞彤芸文化传播股份有限公司 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package wanglijun.vip.androidutils.utils; 19 | 20 | import android.text.TextUtils; 21 | 22 | import java.io.File; 23 | import java.io.IOException; 24 | import java.math.BigDecimal; 25 | 26 | 27 | /** 28 | * @author wlj 29 | * @date 2018/09/01 30 | * @email wanglijundev@gmail.com 31 | * @packagename wanglijun.vip.androidutils 32 | * @description 获取文件大小的类 33 | */ 34 | public class FileSize { 35 | 36 | public static final long SIZE_BT = 1024L; 37 | 38 | public static final long SIZE_KB = SIZE_BT * 1024L; 39 | 40 | public static final long SIZE_MB = SIZE_KB * 1024L; 41 | 42 | public static final long SIZE_GB = SIZE_MB * 1024L; 43 | 44 | public static final long SIZE_TB = SIZE_GB * 1024L; 45 | 46 | public static final int SACLE = 2; 47 | 48 | private File file; 49 | 50 | private long longSize; 51 | 52 | public FileSize(File file) { 53 | this.file = file; 54 | } 55 | 56 | private void getFileSize() throws RuntimeException, IOException { 57 | getFileSize(file); 58 | } 59 | 60 | private void getFileSize(File file) { 61 | 62 | if (file == null || !file.exists()) { 63 | return; 64 | } 65 | 66 | if (file.isFile()) { 67 | this.longSize += file.length(); 68 | return; 69 | } 70 | 71 | File[] childArray = file.listFiles(); 72 | if (childArray == null || childArray.length == 0) { 73 | return; 74 | } 75 | 76 | for (File child : childArray) { 77 | getFileSize(child); 78 | } 79 | 80 | } 81 | 82 | @Override 83 | public String toString() throws RuntimeException { 84 | try { 85 | try { 86 | getFileSize(); 87 | } catch (RuntimeException e) { 88 | return ""; 89 | } 90 | 91 | return convertSizeToString(this.longSize); 92 | 93 | } catch (IOException ex) { 94 | ex.printStackTrace(); 95 | throw new RuntimeException(ex.getMessage()); 96 | } 97 | } 98 | 99 | /** 100 | * 格式化输出文件大小 101 | * @param fileSize 102 | * @return 103 | */ 104 | public static String convertSizeToString(long fileSize) { 105 | if (fileSize >= 0 && fileSize < SIZE_BT) { 106 | return fileSize + "B"; 107 | } else if (fileSize >= SIZE_BT && fileSize < SIZE_KB) { 108 | return fileSize / SIZE_BT + "KB"; 109 | } else if (fileSize >= SIZE_KB && fileSize < SIZE_MB) { 110 | return fileSize / SIZE_KB + "MB"; 111 | } else if (fileSize >= SIZE_MB && fileSize < SIZE_GB) { 112 | BigDecimal longs = new BigDecimal(Double.valueOf(fileSize + "").toString()); 113 | BigDecimal sizeMB = new BigDecimal(Double.valueOf(SIZE_MB + "").toString()); 114 | String result = longs.divide(sizeMB, SACLE, BigDecimal.ROUND_HALF_UP).toString(); 115 | // double result=this.longSize/(double)SIZE_MB; 116 | return result + "GB"; 117 | } else { 118 | BigDecimal longs = new BigDecimal(Double.valueOf(fileSize + "").toString()); 119 | BigDecimal sizeMB = new BigDecimal(Double.valueOf(SIZE_GB + "").toString()); 120 | String result = longs.divide(sizeMB, SACLE, BigDecimal.ROUND_HALF_UP).toString(); 121 | return result + "TB"; 122 | } 123 | } 124 | 125 | /** 126 | * MB转KB 127 | * @param fileSize 128 | * @return 129 | */ 130 | public static double getKBSize(String fileSize) { 131 | if (TextUtils.isEmpty(fileSize)) { 132 | return 0; 133 | } 134 | fileSize = fileSize.toUpperCase(); 135 | int index; 136 | if ((index = fileSize.indexOf("MB")) > 0) { 137 | String str = fileSize.substring(0, index).trim(); 138 | return string2double(str) * 1024; 139 | } 140 | if ((index = fileSize.indexOf("KB")) > 0) { 141 | String str = fileSize.substring(0, index).trim(); 142 | return string2double(str); 143 | } 144 | return 0; 145 | } 146 | 147 | public static double string2double(String doubleStr) { 148 | try { 149 | return Double.parseDouble(doubleStr); 150 | } catch (Exception e) { 151 | } 152 | return 0; 153 | } 154 | 155 | /** 156 | * 获取文件的大小单位是byte 157 | * @return 返回文件的大小 158 | * @throws RuntimeException 159 | */ 160 | public long getLongSize() throws RuntimeException { 161 | try { 162 | 163 | getFileSize(); 164 | return longSize; 165 | } catch (IOException ex) { 166 | ex.printStackTrace(); 167 | throw new RuntimeException(ex.getMessage()); 168 | } 169 | } 170 | 171 | } 172 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/FileUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.FileNotFoundException; 7 | import java.io.FileOutputStream; 8 | import java.io.FileWriter; 9 | import java.io.IOException; 10 | import java.io.InputStream; 11 | import java.io.InputStreamReader; 12 | import java.io.OutputStream; 13 | 14 | /** 15 | * @author: wlj 16 | * @Date: 2017-03-28 17 | * @email: wanglijundev@gmail.com 18 | * @desc: 文件工具类 19 | */ 20 | public class FileUtils { 21 | 22 | public final static String FILE_SUFFIX_SEPARATOR = "."; 23 | 24 | /** 25 | * Read file 26 | * 27 | * @param filePath 28 | * @param charsetName 29 | * @return 30 | */ 31 | public static StringBuilder readFile(String filePath, String charsetName) { 32 | File file = new File(filePath); 33 | StringBuilder fileContent = new StringBuilder(""); 34 | if (!file.isFile()) { 35 | return null; 36 | } 37 | 38 | BufferedReader reader = null; 39 | try { 40 | InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName); 41 | reader = new BufferedReader(is); 42 | String line = null; 43 | while ((line = reader.readLine()) != null) { 44 | if (!"".equals(fileContent.toString())) { 45 | fileContent.append("\r\n"); 46 | } 47 | fileContent.append(line); 48 | } 49 | return fileContent; 50 | } catch (IOException e) { 51 | throw new RuntimeException("IOException", e); 52 | } finally { 53 | IOUtils.close(reader); 54 | } 55 | } 56 | 57 | /** 58 | * Write file 59 | * 60 | * @param filePath 61 | * @param content 62 | * @param append 63 | * @return 64 | */ 65 | public static boolean writeFile(String filePath, String content, boolean append) { 66 | if (StringUtils.isEmpty(content)) { 67 | return false; 68 | } 69 | FileWriter fileWriter = null; 70 | try { 71 | makeDirs(filePath); 72 | fileWriter = new FileWriter(filePath, append); 73 | fileWriter.write(content); 74 | return true; 75 | } catch (IOException e) { 76 | throw new RuntimeException("IOException occurred. ", e); 77 | } finally { 78 | IOUtils.close(fileWriter); 79 | } 80 | } 81 | 82 | /** 83 | * write file, the string will be written to the begin of the file 84 | * 85 | * @param filePath 86 | * @param content 87 | * @return 88 | */ 89 | public static boolean writeFile(String filePath, String content) { 90 | return writeFile(filePath, content, false); 91 | } 92 | 93 | /** 94 | * Write file 95 | * 96 | * @param filePath 97 | * @param is 98 | * @return 99 | */ 100 | public static boolean writeFile(String filePath, InputStream is) { 101 | return writeFile(filePath, is, false); 102 | } 103 | 104 | /** 105 | * Write file 106 | * 107 | * @param filePath 108 | * @param is 109 | * @param append 110 | * @return 111 | */ 112 | public static boolean writeFile(String filePath, InputStream is, boolean append) { 113 | return writeFile(filePath != null ? new File(filePath) : null, is, append); 114 | } 115 | 116 | /** 117 | * Write file 118 | * 119 | * @param file 120 | * @param is 121 | * @return 122 | */ 123 | public static boolean writeFile(File file, InputStream is) { 124 | return writeFile(file, is, false); 125 | } 126 | 127 | /** 128 | * Write file 129 | * 130 | * @param file 131 | * @param is 132 | * @param append 133 | * @return 134 | */ 135 | public static boolean writeFile(File file, InputStream is, boolean append) { 136 | OutputStream o = null; 137 | try { 138 | makeDirs(file.getAbsolutePath()); 139 | o = new FileOutputStream(file, append); 140 | byte[] data = new byte[1024]; 141 | int length = -1; 142 | while ((length = is.read(data)) != -1) { 143 | o.write(data, 0, length); 144 | } 145 | o.flush(); 146 | return true; 147 | } catch (FileNotFoundException e) { 148 | throw new RuntimeException("FileNotFoundException", e); 149 | } catch (IOException e) { 150 | throw new RuntimeException("IOException", e); 151 | } finally { 152 | IOUtils.close(o); 153 | IOUtils.close(is); 154 | } 155 | } 156 | 157 | /** 158 | * Move file 159 | * 160 | * @param srcFilePath 161 | * @param destFilePath 162 | */ 163 | public static void moveFile(String srcFilePath, String destFilePath) throws FileNotFoundException { 164 | if (StringUtils.isEmpty(srcFilePath) || StringUtils.isEmpty(destFilePath)) { 165 | throw new RuntimeException("Both srcFilePath and destFilePath cannot be null."); 166 | } 167 | moveFile(new File(srcFilePath), new File(destFilePath)); 168 | } 169 | 170 | /** 171 | * Move file 172 | * 173 | * @param srcFile 174 | * @param destFile 175 | */ 176 | public static void moveFile(File srcFile, File destFile) throws FileNotFoundException { 177 | boolean rename = srcFile.renameTo(destFile); 178 | if (!rename) { 179 | copyFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath()); 180 | deleteFile(srcFile.getAbsolutePath()); 181 | } 182 | } 183 | 184 | /** 185 | * Copy file 186 | * 187 | * @param srcFilePath 188 | * @param destFilePath 189 | * @return 190 | * @throws FileNotFoundException 191 | */ 192 | public static boolean copyFile(String srcFilePath, String destFilePath) throws FileNotFoundException { 193 | InputStream inputStream = new FileInputStream(srcFilePath); 194 | return writeFile(destFilePath, inputStream); 195 | } 196 | 197 | /** 198 | * rename file 199 | * 200 | * @param file 201 | * @param newFileName 202 | * @return 203 | */ 204 | public static boolean renameFile(File file, String newFileName) { 205 | File newFile = null; 206 | if (file.isDirectory()) { 207 | newFile = new File(file.getParentFile(), newFileName); 208 | } else { 209 | String temp = newFileName 210 | + file.getName().substring( 211 | file.getName().lastIndexOf('.')); 212 | newFile = new File(file.getParentFile(), temp); 213 | } 214 | if (file.renameTo(newFile)) { 215 | return true; 216 | } 217 | return false; 218 | } 219 | 220 | /** 221 | * Get file name without suffix 222 | * 223 | * @param filePath 224 | * @return 225 | */ 226 | public static String getFileNameWithoutSuffix(String filePath) { 227 | if (StringUtils.isEmpty(filePath)) { 228 | return filePath; 229 | } 230 | int suffix = filePath.lastIndexOf(FILE_SUFFIX_SEPARATOR); 231 | int fp = filePath.lastIndexOf(File.separator); 232 | if (fp == -1) { 233 | return (suffix == -1 ? filePath : filePath.substring(0, suffix)); 234 | } 235 | if (suffix == -1) { 236 | return filePath.substring(fp + 1); 237 | } 238 | return (fp < suffix ? filePath.substring(fp + 1, suffix) : filePath.substring(fp + 1)); 239 | } 240 | 241 | /** 242 | * Get file name 243 | * 244 | * @param filePath 245 | * @return 246 | */ 247 | public static String getFileName(String filePath) { 248 | if (StringUtils.isEmpty(filePath)) { 249 | return filePath; 250 | } 251 | int fp = filePath.lastIndexOf(File.separator); 252 | return (fp == -1) ? filePath : filePath.substring(fp + 1); 253 | } 254 | 255 | /** 256 | * Get folder name 257 | * 258 | * @param filePath 259 | * @return 260 | */ 261 | public static String getFolderName(String filePath) { 262 | if (StringUtils.isEmpty(filePath)) { 263 | return filePath; 264 | } 265 | int fp = filePath.lastIndexOf(File.separator); 266 | return (fp == -1) ? "" : filePath.substring(0, fp); 267 | } 268 | 269 | /** 270 | * Get suffix of file 271 | * 272 | * @param filePath 273 | * @return 274 | */ 275 | public static String getFileSuffix(String filePath) { 276 | if (StringUtils.isEmpty(filePath)) { 277 | return filePath; 278 | } 279 | int suffix = filePath.lastIndexOf(FILE_SUFFIX_SEPARATOR); 280 | int fp = filePath.lastIndexOf(File.separator); 281 | if (suffix == -1) { 282 | return ""; 283 | } 284 | return (fp >= suffix) ? "" : filePath.substring(suffix + 1); 285 | } 286 | 287 | /** 288 | * Create the directory 289 | * 290 | * @param filePath 291 | * @return 292 | */ 293 | public static boolean makeDirs(String filePath) { 294 | String folderName = getFolderName(filePath); 295 | if (StringUtils.isEmpty(folderName)) { 296 | return false; 297 | } 298 | File folder = new File(folderName); 299 | return (folder.exists() && folder.isDirectory()) || folder.mkdirs(); 300 | } 301 | 302 | /** 303 | * Judge whether a file is exist 304 | * 305 | * @param filePath 306 | * @return 307 | */ 308 | public static boolean isFileExist(String filePath) { 309 | if (StringUtils.isEmpty(filePath)) { 310 | return false; 311 | } 312 | File file = new File(filePath); 313 | return (file.exists() && file.isFile()); 314 | } 315 | 316 | /** 317 | * Judge whether a folder is exist 318 | * 319 | * @param directoryPath 320 | * @return 321 | */ 322 | public static boolean isFolderExist(String directoryPath) { 323 | if (StringUtils.isEmpty(directoryPath)) { 324 | return false; 325 | } 326 | File dire = new File(directoryPath); 327 | return (dire.exists() && dire.isDirectory()); 328 | } 329 | 330 | /** 331 | * Delete file or folder 332 | * 333 | * @param path 334 | * @return 335 | */ 336 | public static boolean deleteFile(String path) { 337 | if (StringUtils.isEmpty(path)) { 338 | return true; 339 | } 340 | 341 | File file = new File(path); 342 | if (!file.exists()) { 343 | return true; 344 | } 345 | if (file.isFile()) { 346 | return file.delete(); 347 | } 348 | if (!file.isDirectory()) { 349 | return false; 350 | } 351 | if (file.isDirectory()) { 352 | for (File f : file.listFiles()) { 353 | if (f.isFile()) { 354 | f.delete(); 355 | } else if (f.isDirectory()) { 356 | deleteFile(f.getAbsolutePath()); 357 | } 358 | } 359 | } 360 | return file.delete(); 361 | } 362 | 363 | /** 364 | * Delete file or folder 365 | * 366 | * @param file 367 | * @return 368 | */ 369 | public static boolean deleteFile(File file) { 370 | if (!file.exists()) { 371 | return true; 372 | } 373 | if (file.isFile()) { 374 | return file.delete(); 375 | } 376 | if (!file.isDirectory()) { 377 | return false; 378 | } 379 | file.isDirectory(); 380 | File[] childFile = file.listFiles(); 381 | if (childFile == null || childFile.length == 0) { 382 | return file.delete(); 383 | } 384 | for (File f : childFile) { 385 | deleteFile(f); 386 | } 387 | return file.delete(); 388 | } 389 | 390 | /** 391 | * Get file size 392 | * 393 | * @param path 394 | * @return 395 | */ 396 | public static long getFileSize(String path) { 397 | if (StringUtils.isEmpty(path)) { 398 | return -1; 399 | } 400 | File file = new File(path); 401 | return (file.exists() && file.isFile() ? file.length() : -1); 402 | } 403 | 404 | /** 405 | * Get folder size 406 | * 407 | * @param file 408 | * @return 409 | * @throws Exception 410 | */ 411 | public static long getFolderSize(File file) throws Exception { 412 | long size = 0; 413 | try { 414 | File[] fileList = file.listFiles(); 415 | for (int i = 0; i < fileList.length; i++) { 416 | if (fileList[i].isDirectory()) { 417 | size = size + getFolderSize(fileList[i]); 418 | } else { 419 | size = size + fileList[i].length(); 420 | } 421 | } 422 | } catch (Exception e) { 423 | e.printStackTrace(); 424 | } 425 | return size; 426 | } 427 | } 428 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/IOUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import java.io.Closeable; 4 | import java.io.IOException; 5 | 6 | /** 7 | * @author wlj 8 | * @date 2017/3/29 9 | * @email wanglijundev@gmail.com 10 | * @packagename wanglijun.vip.androidutils.utils 11 | * @desc: io操作 12 | */ 13 | 14 | public class IOUtils { 15 | /** 16 | * Close closeable object 17 | * 关闭可以关闭的对象 18 | * 19 | * @param closeable 20 | */ 21 | public static void close(Closeable closeable) { 22 | if (closeable != null) { 23 | try { 24 | closeable.close(); 25 | } catch (IOException e) { 26 | LogUtils.d("IOUtils",e.toString()); 27 | } 28 | } 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /app/src/main/java/wanglijun/vip/androidutils/utils/JsonUtils.java: -------------------------------------------------------------------------------- 1 | package wanglijun.vip.androidutils.utils; 2 | 3 | import com.google.gson.Gson; 4 | import com.google.gson.reflect.TypeToken; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | /** 11 | * @author wlj 12 | * @date 2017/3/29 13 | * @email wanglijundev@gmail.com 14 | * @packagename wanglijun.vip.androidutils.utils 15 | * @desc: json的转换 16 | */ 17 | 18 | public class JsonUtils { 19 | /** 20 | * Convert object, list, ... to Json 21 | * 转为json格式输出 22 | * @param obj 23 | * @return 24 | */ 25 | public static String toJson(Object obj) { 26 | Gson gson = new Gson(); 27 | return gson.toJson(obj); 28 | } 29 | 30 | /** 31 | * Convert a json string to Object 32 | * 将json转为object对象 33 | * @param json 34 | * @param clazz 35 | * @return 36 | */ 37 | public static