删除部分无用工具类
This commit is contained in:
@@ -1,24 +0,0 @@
|
||||
package com.chwl.library.utils;
|
||||
|
||||
|
||||
/**
|
||||
* Created by lijun on 2014/11/20.
|
||||
*/
|
||||
public class ColorUtil {
|
||||
|
||||
public static String color2HexString(int intColor) {
|
||||
String strColor = String.format("#%06X", 0xFFFFFF & intColor);
|
||||
return strColor;
|
||||
}
|
||||
|
||||
public static float brightness(int color) {
|
||||
int r = (color >> 16) & 0xFF;
|
||||
int g = (color >> 8) & 0xFF;
|
||||
int b = color & 0xFF;
|
||||
|
||||
int V = Math.max(b, Math.max(r, g));
|
||||
|
||||
return (V / 255.f);
|
||||
}
|
||||
|
||||
}
|
@@ -1,147 +0,0 @@
|
||||
package com.chwl.library.utils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
import okio.Okio;
|
||||
|
||||
/**
|
||||
* <p> 文件操作工具类 </p>
|
||||
*
|
||||
* @author jiahui
|
||||
* @date 2018/2/5
|
||||
*/
|
||||
public final class FileUtils {
|
||||
|
||||
/**
|
||||
* 获取文件扩展名
|
||||
*
|
||||
* @param filename 文件路径
|
||||
* @return 扩展名,如:zip,如果文件没有扩展名返回null
|
||||
*/
|
||||
public static String getExtensionName(String filename) {
|
||||
if ((filename != null) && (filename.length() > 0)) {
|
||||
int dot = filename.lastIndexOf('.');
|
||||
if ((dot > -1) && (dot < (filename.length() - 1))) {
|
||||
return filename.substring(dot + 1);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取不带扩展名的文件名
|
||||
*
|
||||
* @param filename 目标文件路径
|
||||
* @return 文件名
|
||||
*/
|
||||
public static String getFileNameNoEx(String filename) {
|
||||
if ((filename != null) && (filename.length() > 0)) {
|
||||
int dot = filename.lastIndexOf('.');
|
||||
if ((dot > -1) && (dot < (filename.length()))) {
|
||||
return filename.substring(0, dot);
|
||||
}
|
||||
}
|
||||
return filename;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件路径的最后文件名(不带扩展名)
|
||||
*
|
||||
* @param filename 目标文件路径
|
||||
* @return 最后文件名(不带扩展名)
|
||||
*/
|
||||
public static String getLastFileNameNoEx(String filename) {
|
||||
if ((filename != null) && (filename.length() > 0)) {
|
||||
int separator = filename.lastIndexOf(File.separator);
|
||||
if (separator > -1 && separator < filename.length()) {
|
||||
String lastName = filename.substring(separator + 1);
|
||||
int dot = lastName.lastIndexOf('.');
|
||||
if ((dot > -1) && (dot < (lastName.length()))) {
|
||||
return lastName.substring(0, dot);
|
||||
} else {
|
||||
return lastName;
|
||||
}
|
||||
}
|
||||
}
|
||||
return filename;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取zip报里面的文件或文件夹列表集合
|
||||
*
|
||||
* @param zipFilePath zip路径
|
||||
* @param bContainFolder 是否包含文件夹
|
||||
* @param bContainFile 是否包含文件
|
||||
* @return zip里面的文件列表集合
|
||||
*/
|
||||
public static List<File> getZipFileList(String zipFilePath, boolean bContainFolder, boolean bContainFile) {
|
||||
List<File> fileList = new ArrayList<>();
|
||||
ZipInputStream inZip = null;
|
||||
try {
|
||||
inZip = new ZipInputStream(new FileInputStream(zipFilePath));
|
||||
ZipEntry zipEntry;
|
||||
String szName;
|
||||
while ((zipEntry = inZip.getNextEntry()) != null) {
|
||||
szName = zipEntry.getName();
|
||||
if (zipEntry.isDirectory()) {
|
||||
szName = szName.substring(0, szName.length() - 1);
|
||||
if (bContainFolder)
|
||||
fileList.add(new File(szName));
|
||||
} else {
|
||||
if (bContainFile)
|
||||
fileList.add(new File(szName));
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
IOUtils.close(inZip);
|
||||
}
|
||||
return fileList;
|
||||
}
|
||||
|
||||
public static void copy(String srcFilePath, String destFilePath) {
|
||||
try {
|
||||
File destFile = new File(destFilePath);
|
||||
Okio.buffer(Okio.sink(destFile)).writeAll(Okio.buffer(Okio.source(new File(srcFilePath))));
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void write(File destFile, String content) {
|
||||
try {
|
||||
Okio.buffer(Okio.appendingSink(destFile))
|
||||
.writeUtf8(content + "\n\n")
|
||||
.flush();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void write(String destFile, String content) {
|
||||
write(new File(destFile), content);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件名
|
||||
*
|
||||
* @param filepath
|
||||
* @return
|
||||
*/
|
||||
public static String getFileNameFromPath(String filepath) {
|
||||
if ((filepath != null) && (filepath.length() > 0)) {
|
||||
int sep = filepath.lastIndexOf('/');
|
||||
if ((sep > -1) && (sep < filepath.length() - 1)) {
|
||||
return filepath.substring(sep + 1);
|
||||
}
|
||||
}
|
||||
return filepath;
|
||||
}
|
||||
}
|
@@ -1,246 +0,0 @@
|
||||
package com.chwl.library.utils;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.graphics.Matrix;
|
||||
import android.graphics.drawable.BitmapDrawable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.media.ExifInterface;
|
||||
import android.widget.ImageView;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.lang.ref.SoftReference;
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
|
||||
public class ImageUtils {
|
||||
|
||||
public static Bitmap path2Bitmap(String path, int w, int h){
|
||||
BitmapFactory.Options opts = new BitmapFactory.Options();
|
||||
// 设置为ture只获取图片大小
|
||||
opts.inJustDecodeBounds = true;
|
||||
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
|
||||
// 返回为空
|
||||
BitmapFactory.decodeFile(path, opts);
|
||||
int width = opts.outWidth;
|
||||
int height = opts.outHeight;
|
||||
float scaleWidth = 0.f, scaleHeight = 0.f;
|
||||
if (width > w || height > h) {
|
||||
// 缩放
|
||||
scaleWidth = ((float) width) / w;
|
||||
scaleHeight = ((float) height) / h;
|
||||
}
|
||||
opts.inJustDecodeBounds = false;
|
||||
float scale = Math.max(scaleWidth, scaleHeight);
|
||||
opts.inSampleSize = (int)scale;
|
||||
WeakReference<Bitmap> weak = new WeakReference<Bitmap>(BitmapFactory.decodeFile(path, opts));
|
||||
return Bitmap.createScaledBitmap(weak.get(), w, h, true);
|
||||
}
|
||||
|
||||
public static Bitmap ImageView2Bitmap(ImageView iv){
|
||||
if(null != iv && null != iv.getDrawable()){
|
||||
Bitmap image = ((BitmapDrawable)iv.getDrawable()).getBitmap();
|
||||
return image;
|
||||
}else{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void recycle(ImageView iv) {
|
||||
if(null != iv){
|
||||
Bitmap pBitmap = ImageView2Bitmap(iv);
|
||||
if(null != pBitmap){
|
||||
SoftReference<Bitmap> bitmap;
|
||||
bitmap = new SoftReference<Bitmap>(pBitmap);
|
||||
if (bitmap != null) {
|
||||
if (bitmap.get() != null && !bitmap.get().isRecycled()) {
|
||||
// bitmap.get().recycle();
|
||||
bitmap = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 等比例缩放图片
|
||||
public static Bitmap zoomImg(String imgPath, int newWidth, int newHeight) {
|
||||
|
||||
// 图片源
|
||||
Bitmap bm = BitmapFactory.decodeFile(imgPath);
|
||||
if (null != bm) {
|
||||
return zoomImg(bm, newWidth, newHeight);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Bitmap zoomImg(Context context, String img, int newWidth, int newHeight) {
|
||||
// 图片源
|
||||
try {
|
||||
Bitmap bm = BitmapFactory.decodeStream(context.getAssets().open(img));
|
||||
if (null != bm) {
|
||||
return zoomImg(bm, newWidth, newHeight);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// 缩放图片
|
||||
public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
|
||||
// 获得图片的宽高
|
||||
int width = bm.getWidth();
|
||||
int height = bm.getHeight();
|
||||
// 计算缩放比例
|
||||
float scaleWidth = ((float) newWidth) / width;
|
||||
float scaleHeight = ((float) newHeight) / height;
|
||||
// 取得想要缩放的matrix参数
|
||||
Matrix matrix = new Matrix();
|
||||
matrix.postScale(scaleWidth, scaleHeight);
|
||||
// 得到新的图片
|
||||
Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
|
||||
bm = null;
|
||||
return newbm;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据图片的url路径获得Bitmap对象
|
||||
*
|
||||
* @param url
|
||||
* @return
|
||||
*/
|
||||
public static Bitmap urlToBitmap(String url) {
|
||||
URL fileUrl = null;
|
||||
Bitmap bitmap = null;
|
||||
|
||||
try {
|
||||
fileUrl = new URL(url);
|
||||
} catch (MalformedURLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
try {
|
||||
HttpURLConnection conn = (HttpURLConnection) fileUrl.openConnection();
|
||||
conn.setDoInput(true);
|
||||
conn.connect();
|
||||
InputStream is = conn.getInputStream();
|
||||
bitmap = BitmapFactory.decodeStream(is);
|
||||
is.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return bitmap;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param urlpath
|
||||
* @return Bitmap 根据图片url获取图片对象
|
||||
*/
|
||||
public static Bitmap getBitMBitmap(String urlpath) {
|
||||
Bitmap map = null;
|
||||
try {
|
||||
URL url = new URL(urlpath);
|
||||
URLConnection conn = url.openConnection();
|
||||
conn.connect();
|
||||
InputStream in;
|
||||
in = conn.getInputStream();
|
||||
map = BitmapFactory.decodeStream(in);
|
||||
// TODO Auto-generated catch block
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param urlpath
|
||||
* @return Bitmap 根据url获取布局背景的对<E79A84>?
|
||||
*/
|
||||
public static Drawable getDrawable(String urlpath) {
|
||||
Drawable d = null;
|
||||
try {
|
||||
URL url = new URL(urlpath);
|
||||
URLConnection conn = url.openConnection();
|
||||
conn.connect();
|
||||
InputStream in;
|
||||
in = conn.getInputStream();
|
||||
d = Drawable.createFromStream(in, "background.jpg");
|
||||
// TODO Auto-generated catch block
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 读取图片的旋转的角度
|
||||
*
|
||||
* @param path
|
||||
* 图片绝对路径
|
||||
* @return 图片的旋转角度
|
||||
*/
|
||||
private int getBitmapDegree(String path) {
|
||||
int degree = 0;
|
||||
try {
|
||||
// 从指定路径下读取图片,并获取其EXIF信息
|
||||
ExifInterface exifInterface = new ExifInterface(path);
|
||||
// 获取图片的旋转信息
|
||||
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
|
||||
ExifInterface.ORIENTATION_NORMAL);
|
||||
switch (orientation) {
|
||||
case ExifInterface.ORIENTATION_ROTATE_90:
|
||||
degree = 90;
|
||||
break;
|
||||
case ExifInterface.ORIENTATION_ROTATE_180:
|
||||
degree = 180;
|
||||
break;
|
||||
case ExifInterface.ORIENTATION_ROTATE_270:
|
||||
degree = 270;
|
||||
break;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return degree;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将图片按照某个角度进行旋转
|
||||
*
|
||||
* @param bm
|
||||
* 需要旋转的图片
|
||||
* @param degree
|
||||
* 旋转角度
|
||||
* @return 旋转后的图片
|
||||
*/
|
||||
public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
|
||||
Bitmap returnBm = null;
|
||||
|
||||
// 根据旋转角度,生成旋转矩阵
|
||||
Matrix matrix = new Matrix();
|
||||
matrix.postRotate(degree);
|
||||
try {
|
||||
// 将原始图片按照旋转矩阵进行旋转,并得到新的图片
|
||||
returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
|
||||
} catch (OutOfMemoryError e) {
|
||||
}
|
||||
if (returnBm == null) {
|
||||
returnBm = bm;
|
||||
}
|
||||
if (bm != returnBm) {
|
||||
bm.recycle();
|
||||
}
|
||||
return returnBm;
|
||||
}
|
||||
|
||||
}
|
@@ -1,379 +0,0 @@
|
||||
package com.chwl.library.utils;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.net.wifi.WifiInfo;
|
||||
import android.net.wifi.WifiManager;
|
||||
import android.os.Build;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
|
||||
import com.chwl.library.BuildConfig;
|
||||
import com.chwl.library.R;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.LineNumberReader;
|
||||
import java.io.Reader;
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.SocketException;
|
||||
import java.util.Enumeration;
|
||||
|
||||
/**
|
||||
* Created by MadisonRong on 2019/7/5
|
||||
*/
|
||||
public class MacAddressUtils {
|
||||
|
||||
public static String getMac(Context context) {
|
||||
|
||||
String strMac = null;
|
||||
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
|
||||
if (BuildConfig.DEBUG) {
|
||||
Log.e("=====", ResUtil.getString(R.string.xchat_android_library_utils_macaddressutils_01));
|
||||
// Toast.makeText(context, ResUtil.getString(R.string.xchat_android_library_utils_macaddressutils_02), Toast.LENGTH_SHORT).show();
|
||||
SingleToastUtil.showToastShort(ResUtil.getString(R.string.xchat_android_library_utils_macaddressutils_03));
|
||||
}
|
||||
strMac = getLocalMacAddressFromWifiInfo(context);
|
||||
return strMac;
|
||||
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N
|
||||
&& Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
if (BuildConfig.DEBUG) {
|
||||
Log.e("=====", ResUtil.getString(R.string.xchat_android_library_utils_macaddressutils_04));
|
||||
// Toast.makeText(context, ResUtil.getString(R.string.xchat_android_library_utils_macaddressutils_05), Toast.LENGTH_SHORT).show();
|
||||
SingleToastUtil.showToastShort(ResUtil.getString(R.string.xchat_android_library_utils_macaddressutils_06));
|
||||
}
|
||||
strMac = getMacAddress(context);
|
||||
return strMac;
|
||||
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||
Log.e("=====", ResUtil.getString(R.string.xchat_android_library_utils_macaddressutils_07));
|
||||
if (!TextUtils.isEmpty(getMacAddress())) {
|
||||
if (BuildConfig.DEBUG) {
|
||||
Log.e("=====", ResUtil.getString(R.string.xchat_android_library_utils_macaddressutils_08));
|
||||
// Toast.makeText(context, ResUtil.getString(R.string.xchat_android_library_utils_macaddressutils_09), Toast.LENGTH_SHORT).show();
|
||||
SingleToastUtil.showToastShort(ResUtil.getString(R.string.xchat_android_library_utils_macaddressutils_010));
|
||||
}
|
||||
strMac = getMacAddress();
|
||||
return strMac;
|
||||
} else if (!TextUtils.isEmpty(getMachineHardwareAddress())) {
|
||||
if (BuildConfig.DEBUG) {
|
||||
Log.e("=====", ResUtil.getString(R.string.xchat_android_library_utils_macaddressutils_011));
|
||||
// Toast.makeText(context, ResUtil.getString(R.string.xchat_android_library_utils_macaddressutils_012), Toast.LENGTH_SHORT).show();
|
||||
SingleToastUtil.showToastShort(ResUtil.getString(R.string.xchat_android_library_utils_macaddressutils_013));
|
||||
}
|
||||
strMac = getMachineHardwareAddress();
|
||||
return strMac;
|
||||
} else {
|
||||
if (BuildConfig.DEBUG) {
|
||||
Log.e("=====", ResUtil.getString(R.string.xchat_android_library_utils_macaddressutils_014));
|
||||
// Toast.makeText(context, ResUtil.getString(R.string.xchat_android_library_utils_macaddressutils_015), Toast.LENGTH_SHORT).show();
|
||||
SingleToastUtil.showToastShort(ResUtil.getString(R.string.xchat_android_library_utils_macaddressutils_016));
|
||||
}
|
||||
strMac = getLocalMacAddressFromBusybox();
|
||||
return strMac;
|
||||
}
|
||||
}
|
||||
|
||||
return "02:00:00:00:00:00";
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据wifi信息获取本地mac
|
||||
* @param context
|
||||
* @return
|
||||
*/
|
||||
public static String getLocalMacAddressFromWifiInfo(Context context) {
|
||||
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
|
||||
WifiInfo winfo = wifi.getConnectionInfo();
|
||||
String mac = winfo.getMacAddress();
|
||||
return mac;
|
||||
}
|
||||
|
||||
/**
|
||||
* android 6.0及以上、7.0以下 获取mac地址
|
||||
*
|
||||
* @param context
|
||||
* @return
|
||||
*/
|
||||
public static String getMacAddress(Context context) {
|
||||
|
||||
// 如果是6.0以下,直接通过wifimanager获取
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
|
||||
String macAddress0 = getMacAddress0(context);
|
||||
if (!TextUtils.isEmpty(macAddress0)) {
|
||||
return macAddress0;
|
||||
}
|
||||
}
|
||||
String str = "";
|
||||
String macSerial = "";
|
||||
try {
|
||||
Process pp = Runtime.getRuntime().exec(
|
||||
"cat /sys/class/net/wlan0/address");
|
||||
InputStreamReader ir = new InputStreamReader(pp.getInputStream());
|
||||
LineNumberReader input = new LineNumberReader(ir);
|
||||
for (; null != str; ) {
|
||||
str = input.readLine();
|
||||
if (str != null) {
|
||||
macSerial = str.trim();// 去空格
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
Log.e("----->" + "NetInfoManager", "getMacAddress:" + ex.toString());
|
||||
}
|
||||
if (macSerial == null || "".equals(macSerial)) {
|
||||
try {
|
||||
return loadFileAsString("/sys/class/net/eth0/address")
|
||||
.toUpperCase().substring(0, 17);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
Log.e("----->" + "NetInfoManager",
|
||||
"getMacAddress:" + e.toString());
|
||||
}
|
||||
|
||||
}
|
||||
return macSerial;
|
||||
}
|
||||
|
||||
private static String getMacAddress0(Context context) {
|
||||
if (isAccessWifiStateAuthorized(context)) {
|
||||
WifiManager wifiMgr = (WifiManager) context
|
||||
.getSystemService(Context.WIFI_SERVICE);
|
||||
WifiInfo wifiInfo = null;
|
||||
try {
|
||||
wifiInfo = wifiMgr.getConnectionInfo();
|
||||
return wifiInfo.getMacAddress();
|
||||
} catch (Exception e) {
|
||||
Log.e("----->" + "NetInfoManager",
|
||||
"getMacAddress0:" + e.toString());
|
||||
}
|
||||
|
||||
}
|
||||
return "";
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether accessing wifi state is permitted
|
||||
*
|
||||
* @param context
|
||||
* @return
|
||||
*/
|
||||
private static boolean isAccessWifiStateAuthorized(Context context) {
|
||||
if (PackageManager.PERMISSION_GRANTED == context
|
||||
.checkCallingOrSelfPermission("android.permission.ACCESS_WIFI_STATE")) {
|
||||
Log.e("----->" + "NetInfoManager", "isAccessWifiStateAuthorized:"
|
||||
+ "access wifi state is enabled");
|
||||
return true;
|
||||
} else
|
||||
return false;
|
||||
}
|
||||
|
||||
private static String loadFileAsString(String fileName) throws Exception {
|
||||
FileReader reader = new FileReader(fileName);
|
||||
String text = loadReaderAsString(reader);
|
||||
reader.close();
|
||||
return text;
|
||||
}
|
||||
|
||||
private static String loadReaderAsString(Reader reader) throws Exception {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
char[] buffer = new char[4096];
|
||||
int readLength = reader.read(buffer);
|
||||
while (readLength >= 0) {
|
||||
builder.append(buffer, 0, readLength);
|
||||
readLength = reader.read(buffer);
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据IP地址获取MAC地址
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static String getMacAddress() {
|
||||
String strMacAddr = null;
|
||||
try {
|
||||
// 获得IpD地址
|
||||
InetAddress ip = getLocalInetAddress();
|
||||
byte[] b = NetworkInterface.getByInetAddress(ip)
|
||||
.getHardwareAddress();
|
||||
StringBuffer buffer = new StringBuffer();
|
||||
for (int i = 0; i < b.length; i++) {
|
||||
if (i != 0) {
|
||||
buffer.append(':');
|
||||
}
|
||||
String str = Integer.toHexString(b[i] & 0xFF);
|
||||
buffer.append(str.length() == 1 ? 0 + str : str);
|
||||
}
|
||||
strMacAddr = buffer.toString().toUpperCase();
|
||||
} catch (Exception e) {
|
||||
}
|
||||
return strMacAddr;
|
||||
}
|
||||
/**
|
||||
* 获取移动设备本地IP
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
private static InetAddress getLocalInetAddress() {
|
||||
InetAddress ip = null;
|
||||
try {
|
||||
// 列举
|
||||
Enumeration<NetworkInterface> en_netInterface = NetworkInterface
|
||||
.getNetworkInterfaces();
|
||||
while (en_netInterface.hasMoreElements()) {// 是否还有元素
|
||||
NetworkInterface ni = (NetworkInterface) en_netInterface
|
||||
.nextElement();// 得到下一个元素
|
||||
Enumeration<InetAddress> en_ip = ni.getInetAddresses();// 得到一个ip地址的列举
|
||||
while (en_ip.hasMoreElements()) {
|
||||
ip = en_ip.nextElement();
|
||||
if (!ip.isLoopbackAddress()
|
||||
&& ip.getHostAddress().indexOf(":") == -1)
|
||||
break;
|
||||
else
|
||||
ip = null;
|
||||
}
|
||||
|
||||
if (ip != null) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (SocketException e) {
|
||||
|
||||
e.printStackTrace();
|
||||
}
|
||||
return ip;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取本地IP
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
private static String getLocalIpAddress() {
|
||||
try {
|
||||
for (Enumeration<NetworkInterface> en = NetworkInterface
|
||||
.getNetworkInterfaces(); en.hasMoreElements(); ) {
|
||||
NetworkInterface intf = en.nextElement();
|
||||
for (Enumeration<InetAddress> enumIpAddr = intf
|
||||
.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
|
||||
InetAddress inetAddress = enumIpAddr.nextElement();
|
||||
if (!inetAddress.isLoopbackAddress()) {
|
||||
return inetAddress.getHostAddress().toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (SocketException ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* android 7.0及以上 (2)扫描各个网络接口获取mac地址
|
||||
*
|
||||
*/
|
||||
/**
|
||||
* 获取设备HardwareAddress地址
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static String getMachineHardwareAddress() {
|
||||
Enumeration<NetworkInterface> interfaces = null;
|
||||
try {
|
||||
interfaces = NetworkInterface.getNetworkInterfaces();
|
||||
} catch (SocketException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
String hardWareAddress = null;
|
||||
NetworkInterface iF = null;
|
||||
if (interfaces == null) {
|
||||
return null;
|
||||
}
|
||||
while (interfaces.hasMoreElements()) {
|
||||
iF = interfaces.nextElement();
|
||||
try {
|
||||
hardWareAddress = bytesToString(iF.getHardwareAddress());
|
||||
if (hardWareAddress != null)
|
||||
break;
|
||||
} catch (SocketException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return hardWareAddress;
|
||||
}
|
||||
|
||||
/***
|
||||
* byte转为String
|
||||
*
|
||||
* @param bytes
|
||||
* @return
|
||||
*/
|
||||
private static String bytesToString(byte[] bytes) {
|
||||
if (bytes == null || bytes.length == 0) {
|
||||
return null;
|
||||
}
|
||||
StringBuilder buf = new StringBuilder();
|
||||
for (byte b : bytes) {
|
||||
buf.append(String.format("%02X:", b));
|
||||
}
|
||||
if (buf.length() > 0) {
|
||||
buf.deleteCharAt(buf.length() - 1);
|
||||
}
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* android 7.0及以上 (3)通过busybox获取本地存储的mac地址
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* 根据busybox获取本地Mac
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static String getLocalMacAddressFromBusybox() {
|
||||
String result = "";
|
||||
String Mac = "";
|
||||
result = callCmd("busybox ifconfig", "HWaddr");
|
||||
// 如果返回的result == null,则说明网络不可取
|
||||
if (result == null) {
|
||||
return ResUtil.getString(R.string.xchat_android_library_utils_macaddressutils_017);
|
||||
}
|
||||
// 对该行数据进行解析
|
||||
// 例如:eth0 Link encap:Ethernet HWaddr 00:16:E8:3E:DF:67
|
||||
if (result.length() > 0 && result.contains("HWaddr") == true) {
|
||||
Mac = result.substring(result.indexOf("HWaddr") + 6,
|
||||
result.length() - 1);
|
||||
result = Mac;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String callCmd(String cmd, String filter) {
|
||||
String result = "";
|
||||
String line = "";
|
||||
try {
|
||||
Process proc = Runtime.getRuntime().exec(cmd);
|
||||
InputStreamReader is = new InputStreamReader(proc.getInputStream());
|
||||
BufferedReader br = new BufferedReader(is);
|
||||
|
||||
while ((line = br.readLine()) != null
|
||||
&& line.contains(filter) == false) {
|
||||
result += line;
|
||||
}
|
||||
|
||||
result = line;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
@@ -1,55 +0,0 @@
|
||||
package com.chwl.library.utils;
|
||||
|
||||
import android.os.Handler;
|
||||
import android.os.Message;
|
||||
|
||||
/**
|
||||
* Created by lijun on 2015/1/29.
|
||||
*/
|
||||
public class OperationTimer extends Handler {
|
||||
|
||||
private static final long SHORT_TIME = 600;
|
||||
public static final int CLICK_MESSAGE = 100;
|
||||
private Callback mCallback;
|
||||
|
||||
private long mShortTime = SHORT_TIME;
|
||||
|
||||
public OperationTimer(long mShortTime, Callback callback) {
|
||||
this(callback);
|
||||
this.mShortTime = mShortTime;
|
||||
}
|
||||
|
||||
public OperationTimer(Callback callback) {
|
||||
this.mCallback = callback;
|
||||
}
|
||||
|
||||
public void setShortTime(long shortTime) {
|
||||
this.mShortTime = shortTime;
|
||||
}
|
||||
|
||||
public void notifyClick() {
|
||||
removeMessages(CLICK_MESSAGE);
|
||||
sendEmptyMessageDelayed(CLICK_MESSAGE, mShortTime);
|
||||
}
|
||||
|
||||
public void stopNotifyClick() {
|
||||
removeMessages(CLICK_MESSAGE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleMessage(Message msg) {
|
||||
switch (msg.what) {
|
||||
case CLICK_MESSAGE:
|
||||
if (null != mCallback) {
|
||||
mCallback.onRealClick();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public interface Callback {
|
||||
public void onRealClick();
|
||||
}
|
||||
}
|
@@ -1,42 +0,0 @@
|
||||
package com.chwl.library.utils;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* Created by MadisonRong on 2019/7/10
|
||||
*/
|
||||
public class RandomStringUtil {
|
||||
|
||||
private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
|
||||
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6',
|
||||
'7', '8', '9'};
|
||||
|
||||
private RandomStringUtil() {
|
||||
}
|
||||
|
||||
public static RandomStringUtil getInstance() {
|
||||
return SingletonHolder.INSTANCE;
|
||||
}
|
||||
|
||||
private static class SingletonHolder {
|
||||
private static final RandomStringUtil INSTANCE = new RandomStringUtil();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取随机String
|
||||
*
|
||||
* @param len
|
||||
* @return
|
||||
*/
|
||||
public static String getRandomString(int len) {
|
||||
String returnStr = "";
|
||||
char[] ch = new char[len];
|
||||
Random rd = new Random();
|
||||
for (int i = 0; i < len; i++) {
|
||||
ch[i] = (char) (rd.nextInt(9) + 65);
|
||||
ch[i] = encodeTable[rd.nextInt(36)];
|
||||
}
|
||||
returnStr = new String(ch);
|
||||
return returnStr;
|
||||
}
|
||||
}
|
@@ -1,103 +0,0 @@
|
||||
package com.chwl.library.utils;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* <p> </p>
|
||||
*
|
||||
* @author jiahui
|
||||
* date 2018/2/28
|
||||
*/
|
||||
public class StringCutUtils {
|
||||
|
||||
private static String regEx = "[\u4e00-\u9fa5]"; // 中文范围
|
||||
|
||||
/**
|
||||
* 格式化字符串
|
||||
* @param string 原始输入字符串
|
||||
* @param maxCount 最大字符限制,中文算作2个字符,其他都算1个字符
|
||||
* @return
|
||||
*/
|
||||
private static String formatText(String string, int maxCount) {
|
||||
if ( (string == null || string.length() == 0)
|
||||
&& getChCount(string) > maxCount) {
|
||||
string = subStrByLen(string, maxCount - 1);
|
||||
}
|
||||
return string;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* 截取字符串,超出最大字数截断并显示"..."
|
||||
* @param str 原始字符串
|
||||
* @param length 最大字数限制(以最大字数限制7个为例,当含中文时,length应设为2*7,不含中文时设为7)
|
||||
* @return 处理后的字符串
|
||||
*/
|
||||
public static String subStrByLen(String str, int length) {
|
||||
if (str == null || str.length() == 0) {
|
||||
return "";
|
||||
}
|
||||
int chCnt = getStrLen(str);
|
||||
// 超出进行截断处理
|
||||
if (chCnt > length) {
|
||||
int cur = 0;
|
||||
int cnt = 0;
|
||||
StringBuilder sb = new StringBuilder();
|
||||
while (cnt <= length && cur < str.length()) {
|
||||
char nextChar = str.charAt(cur);
|
||||
if (isChCharacter(String.valueOf(nextChar))) {
|
||||
cnt += 2;
|
||||
} else {
|
||||
cnt++;
|
||||
}
|
||||
if (cnt <= length) {
|
||||
sb.append(nextChar);
|
||||
} else {
|
||||
return sb.toString() + "...";
|
||||
}
|
||||
cur++;
|
||||
}
|
||||
return sb.toString() + "...";
|
||||
}
|
||||
// 未超出直接返回
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取字符串中的中文字数
|
||||
*/
|
||||
private static int getChCount(String str) {
|
||||
int cnt = 0;
|
||||
Pattern pattern = Pattern.compile(regEx);
|
||||
Matcher matcher = pattern.matcher(str);;
|
||||
while(matcher.find()) {
|
||||
cnt++;
|
||||
}
|
||||
return cnt;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断字符是不是中文
|
||||
*/
|
||||
private static boolean isChCharacter(String str) {
|
||||
if (str == null || str.length() == 0) {
|
||||
return false;
|
||||
}
|
||||
if (str.length() > 1) {
|
||||
return false;
|
||||
}
|
||||
return Pattern.matches(regEx, str);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取字符长度,中文算作2个字符,其他都算1个字符
|
||||
*/
|
||||
public static int getStrLen(String str) {
|
||||
if (str == null || str.length() == 0) {
|
||||
return 0;
|
||||
}
|
||||
return str.length() + getChCount(str);
|
||||
}
|
||||
|
||||
}
|
@@ -1,225 +0,0 @@
|
||||
package com.chwl.library.utils;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
import android.telephony.TelephonyManager;
|
||||
import android.util.Log;
|
||||
|
||||
import com.chwl.library.R;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
|
||||
public class TelephonyUtils {
|
||||
|
||||
private static final String TAG = TelephonyUtils.class.toString();
|
||||
|
||||
public static class ChinaOperator {
|
||||
public static final String CMCC = "CMCC";
|
||||
public static final String CTL = "CTL";
|
||||
public static final String UNICOM = "UNICOM";
|
||||
public static final String UNKNOWN = "Unknown";
|
||||
|
||||
public static final String NAME_CMCC = ResUtil.getString(R.string.xchat_android_library_utils_telephonyutils_01);
|
||||
public static final String NAME_CTL = ResUtil.getString(R.string.xchat_android_library_utils_telephonyutils_02);
|
||||
public static final String NAME_UNICOM = ResUtil.getString(R.string.xchat_android_library_utils_telephonyutils_03);
|
||||
public static final String NAME_UNKNOWN = ResUtil.getString(R.string.xchat_android_library_utils_telephonyutils_04);
|
||||
}
|
||||
|
||||
public static String getSimOperator(Context c) {
|
||||
TelephonyManager tm = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
|
||||
return tm.getSimOperator();
|
||||
}
|
||||
|
||||
public static String getOperator(Context c) {
|
||||
String sim = getSimOperator(c);
|
||||
if (BlankUtil.isBlank(sim)) {
|
||||
Log.i(TAG, "No sim operator.");
|
||||
return ChinaOperator.UNKNOWN;
|
||||
}
|
||||
if (sim.startsWith("46003") || sim.startsWith("46005")) {
|
||||
return ChinaOperator.CTL;
|
||||
} else if (sim.startsWith("46001") || sim.startsWith("46006")) {
|
||||
return ChinaOperator.UNICOM;
|
||||
} else if (sim.startsWith("46000") || sim.startsWith("46002")
|
||||
|| sim.startsWith("46007") || sim.startsWith("46020")) {
|
||||
return ChinaOperator.CMCC;
|
||||
} else {
|
||||
return ChinaOperator.UNKNOWN;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getOperatorName(Context c) {
|
||||
String sim = getSimOperator(c);
|
||||
if (BlankUtil.isBlank(sim)) {
|
||||
Log.i(TAG, "No sim operator.");
|
||||
return ChinaOperator.NAME_UNKNOWN;
|
||||
}
|
||||
|
||||
if (sim.startsWith("46003") || sim.startsWith("46005")) {
|
||||
return ChinaOperator.NAME_CTL;
|
||||
} else if (sim.startsWith("46001") || sim.startsWith("46006")) {
|
||||
return ChinaOperator.NAME_UNICOM;
|
||||
} else if (sim.startsWith("46000") || sim.startsWith("46002")
|
||||
|| sim.startsWith("46007") || sim.startsWith("46020")) {
|
||||
return ChinaOperator.NAME_CMCC;
|
||||
} else {
|
||||
return ChinaOperator.NAME_UNKNOWN;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getPhoneNumber(Context c) {
|
||||
TelephonyManager tMgr = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
|
||||
String phoneNumber = tMgr.getLine1Number();
|
||||
return phoneNumber;
|
||||
}
|
||||
|
||||
public static boolean hasSimCard(Context c) {
|
||||
return isSIMCardOK(c);
|
||||
}
|
||||
|
||||
private static boolean isSIMCardOK(Context c) {
|
||||
TelephonyManager telMgr = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
|
||||
int s = telMgr.getSimState();
|
||||
Log.i(TelephonyUtils.class.toString(), "SIM state = " + s);
|
||||
|
||||
if (s == TelephonyManager.SIM_STATE_READY) {
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean isDual = isDualSIM(c);
|
||||
|
||||
if (isDual && s != TelephonyManager.SIM_STATE_ABSENT) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean isDualSIM(Context c) {
|
||||
try {
|
||||
Class<android.telephony.SmsManager> smsManagerClass = android.telephony.SmsManager.class;
|
||||
Method[] methods = smsManagerClass.getDeclaredMethods();
|
||||
|
||||
int num = 0;
|
||||
int publicNum = 0;
|
||||
for (Method e : methods) {
|
||||
if (e.getName().equals("sendTextMessage")) {
|
||||
++num;
|
||||
if (Modifier.isPublic(e.getModifiers())) {
|
||||
++publicNum;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Log.i(TelephonyUtils.class.toString(), "There are " + num + " sendTextMessage methods.");
|
||||
return publicNum >= 2;
|
||||
} catch (Throwable e) {
|
||||
Log.e(TelephonyUtils.class.toString(), "Exeption when printSmsAPI " + e.toString());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean isMtkDualSIM(Context c) {
|
||||
boolean dual = false;
|
||||
Method method = null;
|
||||
Object result0 = null;
|
||||
Object result1 = null;
|
||||
TelephonyManager tm = (TelephonyManager) c
|
||||
.getSystemService(Context.TELEPHONY_SERVICE);
|
||||
try {
|
||||
// only works for MTK chip.
|
||||
method = TelephonyManager.class.getMethod("getSimStateGemini",
|
||||
new Class[]{int.class});
|
||||
result0 = method.invoke(tm, new Object[]{Integer.valueOf(0)});
|
||||
result1 = method.invoke(tm, new Object[]{Integer.valueOf(1)});
|
||||
Log.i(NetworkUtils.class.toString(), "isDualSIM check " + result0 + ", " + result1);
|
||||
dual = true;
|
||||
} catch (Exception e) {
|
||||
Log.e(NetworkUtils.class.toString(), "call MTK API getSimStateGemini e = " + e);
|
||||
}
|
||||
return dual;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get dual SIM card states for MTK chip.
|
||||
*
|
||||
* @param c
|
||||
* @param twoOuts Input, two length array, for output. The meaning is dignified
|
||||
* by TelephonyManager.SIM_STATE_XXX.
|
||||
* @return True for it is MTK and dual SIM, false otherwise.
|
||||
*/
|
||||
public static boolean getDualSIMStatesForMtk(Context c, int twoOuts[]) {
|
||||
Method method = null;
|
||||
Object result0 = null;
|
||||
Object result1 = null;
|
||||
TelephonyManager tm = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
|
||||
try {
|
||||
// only works for MTK chip.
|
||||
method = TelephonyManager.class.getMethod("getSimStateGemini",
|
||||
new Class[]{int.class});
|
||||
result0 = method.invoke(tm, new Object[]{Integer.valueOf(0)});
|
||||
result1 = method.invoke(tm, new Object[]{Integer.valueOf(1)});
|
||||
Log.i(NetworkUtils.class.toString(), "isDualSIM check " + result0 + ", " + result1);
|
||||
|
||||
if (result0 instanceof Integer) {
|
||||
twoOuts[0] = ((Integer) result0);
|
||||
}
|
||||
if (result1 instanceof Integer) {
|
||||
twoOuts[1] = ((Integer) result1);
|
||||
}
|
||||
return result0 instanceof Integer && result1 instanceof Integer;
|
||||
} catch (Exception e) {
|
||||
Log.i(NetworkUtils.class.toString(), "call MTK API getSimStateGemini e = " + e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获得imsi
|
||||
*
|
||||
* @param context context
|
||||
* @return imsi
|
||||
*/
|
||||
@SuppressLint("MissingPermission")
|
||||
public static String getIMSI(Context context) {
|
||||
String imsi = "";
|
||||
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
|
||||
if (telephonyManager != null) {
|
||||
imsi = telephonyManager.getSubscriberId();
|
||||
}
|
||||
return imsi == null ? "" : imsi;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得imei
|
||||
*
|
||||
* @param c context
|
||||
* @return imei
|
||||
*/
|
||||
public static String getImei(Context c) {
|
||||
try {
|
||||
TelephonyManager manager = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
|
||||
@SuppressLint("MissingPermission") String imei = manager.getDeviceId();
|
||||
if (!BlankUtil.isBlank(imei) && !imei.matches("0+") && !imei.equals("004999010640000"))
|
||||
return imei;
|
||||
} catch (Exception e) {
|
||||
Log.e("getImei", "getImei e occurs : " + e);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public static String getDeviceModel() {
|
||||
return Build.MODEL;
|
||||
}
|
||||
|
||||
public static String getOSVersion() {
|
||||
return Build.VERSION.RELEASE;
|
||||
}
|
||||
|
||||
public static String getOSName() {
|
||||
return "android";
|
||||
}
|
||||
}
|
@@ -1,15 +0,0 @@
|
||||
package com.chwl.library.utils;
|
||||
|
||||
import android.text.InputFilter;
|
||||
import android.widget.EditText;
|
||||
|
||||
/**
|
||||
* create by lvzebiao on 2018/9/12
|
||||
*/
|
||||
public class ViewUtils {
|
||||
|
||||
public static void setEtMaxLength(EditText editText, int maxLength) {
|
||||
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
|
||||
}
|
||||
|
||||
}
|
@@ -1,203 +0,0 @@
|
||||
package com.chwl.library.utils;
|
||||
|
||||
import android.text.TextUtils;
|
||||
|
||||
import com.orhanobut.logger.Logger;
|
||||
import com.chwl.library.R;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.Enumeration;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
import java.util.zip.ZipInputStream;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
/**
|
||||
* <p> 解压工具类 </p>
|
||||
*
|
||||
* @author jiahui
|
||||
* @date 2018/2/5
|
||||
*/
|
||||
public final class ZipUtils {
|
||||
|
||||
private static final String ZIP = "zip";
|
||||
private static final int MAX_BUFFER = 1024 * 8;
|
||||
|
||||
private ZipUtils() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 解压zip到指定的路径
|
||||
* <p><b>
|
||||
* 1,当文件不在磁盘上,比如从网络接收的数据,想边接收边解压,因ZipInputStream是顺序按流的方式读取文件,这种场景实现起来毫无压力。
|
||||
* <p>
|
||||
* 2,如果顺序解压ZIP前面的一小部分文件, ZipFile也不是最佳选择,因为ZipFile读CentralDirectory会带来额外的耗时。
|
||||
* <p>
|
||||
* 3,如果ZIP中CentralDirectory遭到损坏,只能通过ZipInputStream来按顺序解压。</b></p>
|
||||
*
|
||||
* @param srcFile ZIP的名称
|
||||
* @param destFile 要解压缩路径
|
||||
* @return true:成功,false:失败
|
||||
*/
|
||||
public static boolean unZipFolderByZipInputStream(String srcFile, String destFile) {
|
||||
ZipInputStream inZip = null;
|
||||
BufferedOutputStream bos = null;
|
||||
try {
|
||||
inZip = new ZipInputStream(new BufferedInputStream(new FileInputStream(srcFile)));
|
||||
ZipEntry zipEntry;
|
||||
String szName;
|
||||
while ((zipEntry = inZip.getNextEntry()) != null) {
|
||||
szName = zipEntry.getName();
|
||||
if (zipEntry.isDirectory()) {
|
||||
szName = szName.substring(0, szName.length() - 1);
|
||||
File folder = new File(destFile + File.separator + szName);
|
||||
folder.mkdirs();
|
||||
} else {
|
||||
String destFileName = destFile + File.separator + szName;
|
||||
Logger.i(destFileName);
|
||||
File file = new File(destFileName);
|
||||
if (!file.exists()) {
|
||||
Logger.i("create file: " + destFileName);
|
||||
file.getParentFile().mkdirs();
|
||||
file.createNewFile();
|
||||
}
|
||||
bos = new BufferedOutputStream(new FileOutputStream(file));
|
||||
int len;
|
||||
byte[] buffer = new byte[MAX_BUFFER];
|
||||
while ((len = inZip.read(buffer)) != -1) {
|
||||
bos.write(buffer, 0, len);
|
||||
bos.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
IOUtils.close(inZip, bos);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 压缩文件夹
|
||||
*
|
||||
* @param srcFile 源文件路径
|
||||
* @param destFile 输出文件路径,如果是.zip结尾,则使用输出的路径,否则在后面加源文件最后文件名, ../xxx.zip
|
||||
* @return 成功返回最终输出文件,否则返回null
|
||||
*/
|
||||
public static String zipFolder(String srcFile, String destFile) {
|
||||
ZipOutputStream outZip = null;
|
||||
try {
|
||||
String extensionName = FileUtils.getExtensionName(destFile);
|
||||
if (TextUtils.isEmpty(extensionName) || !ZIP.equals(extensionName.toLowerCase())) {
|
||||
String lastFileNameNoEx = FileUtils.getLastFileNameNoEx(srcFile);
|
||||
if (!TextUtils.isEmpty(lastFileNameNoEx)) {
|
||||
destFile = destFile + File.separator + lastFileNameNoEx + "." + ZIP;
|
||||
Logger.i(ResUtil.getString(R.string.xchat_android_library_utils_ziputils_01), destFile);
|
||||
}
|
||||
}
|
||||
outZip = new ZipOutputStream(new FileOutputStream(destFile));
|
||||
File file = new File(srcFile);
|
||||
zipFiles(file.getParent() + File.separator, file.getName(), outZip);
|
||||
outZip.finish();
|
||||
return destFile;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
IOUtils.close(outZip);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 压缩文件
|
||||
*
|
||||
* @param folderName 文件夹
|
||||
* @param fileName 文件名
|
||||
* @param outZip 输出流
|
||||
* @throws IOException 异常
|
||||
*/
|
||||
private static void zipFiles(String folderName, String fileName, ZipOutputStream outZip) throws IOException {
|
||||
if (outZip == null) return;
|
||||
File file = new File(folderName + fileName);
|
||||
if (file.isFile()) {
|
||||
ZipEntry zipEntry = new ZipEntry(fileName);
|
||||
FileInputStream fis = new FileInputStream(file);
|
||||
outZip.putNextEntry(zipEntry);
|
||||
int len;
|
||||
byte[] buffer = new byte[MAX_BUFFER];
|
||||
while ((len = fis.read(buffer)) != -1) {
|
||||
outZip.write(buffer, 0, len);
|
||||
}
|
||||
outZip.closeEntry();
|
||||
} else {
|
||||
String[] fileList = file.list();
|
||||
if (fileList.length <= 0) {
|
||||
ZipEntry zipEntry = new ZipEntry(fileName + File.separator);
|
||||
outZip.putNextEntry(zipEntry);
|
||||
outZip.closeEntry();
|
||||
}
|
||||
for (String name : fileList) {
|
||||
zipFiles(folderName, fileName + File.separator + name, outZip);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解压zip到指定的路径,
|
||||
* <p><b>注意:文件已经在磁盘中存在,且需全部解压出ZIP中的文件,ZipFile效果比ZipInputStream效果好</b></p>
|
||||
*
|
||||
* @param srcFile ZIP的名称
|
||||
* @param destFile 要解压缩路径
|
||||
* @return true:成功,false:失败
|
||||
*/
|
||||
public static boolean unZipFolderByZipFile(String srcFile, String destFile) {
|
||||
InputStream is = null;
|
||||
OutputStream os = null;
|
||||
try {
|
||||
ZipFile zipFile = new ZipFile(srcFile);
|
||||
Enumeration<? extends ZipEntry> entries = zipFile.entries();
|
||||
ZipEntry zipEntry;
|
||||
while (entries.hasMoreElements()) {
|
||||
zipEntry = entries.nextElement();
|
||||
if (zipEntry.isDirectory()) {
|
||||
File folder = new File(destFile + File.separator + zipEntry.getName());
|
||||
folder.mkdirs();
|
||||
} else {
|
||||
String destFileName = destFile + File.separator + zipEntry.getName();
|
||||
Logger.i(destFileName);
|
||||
File file = new File(destFileName);
|
||||
if (!file.exists()) {
|
||||
Logger.i("create file: " + destFileName);
|
||||
file.getParentFile().mkdirs();
|
||||
file.createNewFile();
|
||||
}
|
||||
is = new BufferedInputStream(zipFile.getInputStream(zipEntry));
|
||||
os = new BufferedOutputStream(new FileOutputStream(file));
|
||||
int len;
|
||||
byte[] buffer = new byte[MAX_BUFFER];
|
||||
while ((len = is.read(buffer, 0, buffer.length)) != -1) {
|
||||
os.write(buffer, 0, len);
|
||||
os.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
IOUtils.close(is, os);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
Reference in New Issue
Block a user