代码
public class ConvertUtils {
public static final long GB = 1073741824L;
public static final long MB = 1048576L;
public static final long KB = 1024L;
public ConvertUtils() {
}
public static int toInt(Object obj) {
try {
return Integer.parseInt(obj.toString());
} catch (NumberFormatException var2) {
return -1;
}
}
public static int toInt(byte[] bytes) {
int result = 0;
for (int i = 0; i < bytes.length; ++i) {
byte abyte = bytes[i];
result += (abyte & 255) << 8 * i;
}
return result;
}
public static int toShort(byte first, byte second) {
return (first << 8) + (second & 255);
}
public static long toLong(Object obj) {
try {
return Long.parseLong(obj.toString());
} catch (NumberFormatException var2) {
return -1L;
}
}
public static float toFloat(Object obj) {
try {
return Float.parseFloat(obj.toString());
} catch (NumberFormatException var2) {
return -1.0F;
}
}
public static byte[] toByteArray(int i) {
return ByteBuffer.allocate(4).putInt(i).array();
}
public static byte[] toByteArray(String hexData, boolean isHex) {
if (hexData != null && !hexData.equals("")) {
if (!isHex) {
return hexData.getBytes();
} else {
hexData = hexData.replaceAll("\\s+", "");
String hexDigits = "0123456789ABCDEF";
ByteArrayOutputStream baos = new ByteArrayOutputStream(hexData.length() / 2);
for (int i = 0; i < hexData.length(); i += 2) {
baos.write(hexDigits.indexOf(hexData.charAt(i)) << 4 | hexDigits.indexOf(hexData.charAt(i + 1)));
}
byte[] bytes = baos.toByteArray();
try {
baos.close();
} catch (IOException var6) {
LogUtils.warn(var6);
}
return bytes;
}
} else {
return null;
}
}
public static String toHexString(String str) {
if (TextUtils.isEmpty(str)) {
return "";
} else {
StringBuilder builder = new StringBuilder();
byte[] bytes = str.getBytes();
byte[] var3 = bytes;
int var4 = bytes.length;
for (int var5 = 0; var5 < var4; ++var5) {
byte aByte = var3[var5];
builder.append(Integer.toHexString(255 & aByte));
builder.append(" ");
}
return builder.toString();
}
}
public static String toHexString(byte... bytes) {
char[] DIGITS = new char[]{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
char[] buffer = new char[bytes.length * 2];
int i = 0;
for (int var4 = 0; i < bytes.length; ++i) {
int u = bytes[i] < 0 ? bytes[i] + 256 : bytes[i];
buffer[var4++] = DIGITS[u >>> 4];
buffer[var4++] = DIGITS[u & 15];
}
return new String(buffer);
}
public static String toHexString(int num) {
String hexString = Integer.toHexString(num);
LogUtils.verbose(String.format(Locale.CHINA, "%d to hex string is %s", new Object[]{
Integer.valueOf(num), hexString}));
return hexString;
}
public static String toBinaryString(byte... bytes) {
char[] DIGITS = new char[]{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
char[] buffer = new char[bytes.length * 8];
int i = 0;
for (int var4 = 0; i < bytes.length; ++i) {
int u = bytes[i] < 0 ? bytes[i] + 256 : bytes[i];
buffer[var4++] = DIGITS[u >>> 7 & 1];
buffer[var4++] = DIGITS[u >>> 6 & 1];
buffer[var4++] = DIGITS[u >>> 5 & 1];
buffer[var4++] = DIGITS[u >>> 4 & 1];
buffer[var4++] = DIGITS[u >>> 3 & 1];
buffer[var4++] = DIGITS[u >>> 2 & 1];
buffer[var4++] = DIGITS[u >>> 1 & 1];
buffer[var4++] = DIGITS[u & 1];
}
return new String(buffer);
}
public static String toBinaryString(int num) {
String binaryString = Integer.toBinaryString(num);
LogUtils.verbose(String.format(Locale.CHINA, "%d to binary string is %s", new Object[]{
Integer.valueOf(num), binaryString}));
return binaryString;
}
public static String toSlashString(String str) {
String result = "";
char[] chars = str.toCharArray();
char[] var3 = chars;
int var4 = chars.length;
for (int var5 = 0; var5 < var4; ++var5) {
char chr = var3[var5];
if (chr == 34 || chr == 39 || chr == 92) {
result = result + "\\";
}
result = result + chr;
}
return result;
}
public static <T> T[] toArray(List<T> list) {
return (T[]) list.toArray();
}
public static <T> List<T> toList(T[] array) {
return Arrays.asList(array);
}
public static String toString(Object[] objects) {
return Arrays.deepToString(objects);
}
public static String toString(Object[] objects, String tag) {
StringBuilder sb = new StringBuilder();
Object[] var3 = objects;
int var4 = objects.length;
for (int var5 = 0; var5 < var4; ++var5) {
Object object = var3[var5];
sb.append(object);
sb.append(tag);
}
return sb.toString();
}
public static byte[] toByteArray(InputStream is) {
if (is == null) {
return null;
} else {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buff = new byte[100];
while (true) {
int len = is.read(buff, 0, 100);
if (len == -1) {
byte[] bytes = os.toByteArray();
os.close();
is.close();
return bytes;
}
os.write(buff, 0, len);
}
} catch (IOException var4) {
LogUtils.warn(var4);
return null;
}
}
}
public static byte[] toByteArray(Bitmap bitmap) {
if (bitmap == null) {
return null;
} else {
ByteArrayOutputStream os = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
byte[] bytes = os.toByteArray();
try {
os.close();
} catch (IOException var4) {
LogUtils.warn(var4);
}
return bytes;
}
}
public static Bitmap toBitmap(byte[] bytes, int width, int height) {
Bitmap bitmap = null;
if (bytes.length != 0) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDither = false;
options.inPreferredConfig = null;
if (width > 0 && height > 0) {
options.outWidth = width;
options.outHeight = height;
}
bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
bitmap.setDensity(96);
} catch (Exception var5) {
LogUtils.error(var5);
}
}
return bitmap;
}
public static Bitmap toBitmap(byte[] bytes) {
return toBitmap(bytes, -1, -1);
}
public static Bitmap toBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
} else {
Bitmap bitmap;
Canvas canvas;
if (drawable instanceof ColorDrawable) {
bitmap = Bitmap.createBitmap(32, 32, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
canvas.drawColor(((ColorDrawable) drawable).getColor());
return bitmap;
} else if (drawable instanceof NinePatchDrawable) {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
} else {
return null;
}
}
}
@TargetApi(19)
public static String toPath(Context context, Uri uri) {
if (uri == null) {
LogUtils.verbose("uri is null");
return "";
} else {
LogUtils.verbose("uri: " + uri.toString());
String path = uri.getPath();
String scheme = uri.getScheme();
String authority = uri.getAuthority();
boolean isKitKat = Build.VERSION.SDK_INT >= 19;
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
String docId = DocumentsContract.getDocumentId(uri);
String[] split = docId.split(":");
String type = split[0];
Uri contentUri = null;
byte var11 = -1;
switch (authority.hashCode()) {
case 320699453:
if (authority.equals("com.android.providers.downloads.documents")) {
var11 = 1;
}
break;
case 596745902:
if (authority.equals("com.android.externalstorage.documents")) {
var11 = 0;
}
break;
case 1734583286:
if (authority.equals("com.android.providers.media.documents")) {
var11 = 2;
}
}
switch (var11) {
case 0:
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
break;
case 1:
contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId).longValue());
return _queryPathFromMediaStore(context, contentUri, (String) null, (String[]) null);
case 2:
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
String selection = "_id=?";
String[] selectionArgs = new String[]{
split[1]};
return _queryPathFromMediaStore(context, contentUri, selection, selectionArgs);
}
} else {
if ("content".equalsIgnoreCase(scheme)) {
if (authority.equals("com.google.android.apps.photos.content")) {
return uri.getLastPathSegment();
}
return _queryPathFromMediaStore(context, uri, (String) null, (String[]) null);
}
if ("file".equalsIgnoreCase(scheme)) {
return uri.getPath();
}
}
LogUtils.verbose("uri to path: " + path);
return path;
}
}
private static String _queryPathFromMediaStore(Context context, Uri uri, String selection, String[] selectionArgs) {
String filePath = null;
try {
String[] projection = new String[]{
"_data"};
Cursor cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, (String) null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow("_data");
cursor.moveToFirst();
filePath = cursor.getString(column_index);
cursor.close();
}
} catch (IllegalArgumentException var8) {
LogUtils.error(var8);
}
return filePath;
}
@SuppressLint("WrongConstant")
public static Bitmap toBitmap(View view) {
int width = view.getWidth();
int height = view.getHeight();
int color;
if (view instanceof ListView) {
height = 0;
ListView listView = (ListView) view;
for (color = 0; color < listView.getChildCount(); ++color) {
height += listView.getChildAt(color).getHeight();
}
} else if (view instanceof ScrollView) {
height = 0;
ScrollView scrollView = (ScrollView) view;
for (color = 0; color < scrollView.getChildCount(); ++color) {
height += scrollView.getChildAt(color).getHeight();
}
}
view.setDrawingCacheEnabled(true);
view.clearFocus();
view.setPressed(false);
boolean willNotCache = view.willNotCacheDrawing();
view.setWillNotCacheDrawing(false);
color = view.getDrawingCacheBackgroundColor();
view.setDrawingCacheBackgroundColor(-1);
if (color != -1) {
view.destroyDrawingCache();
}
view.buildDrawingCache();
Bitmap cacheBitmap = view.getDrawingCache();
if (cacheBitmap == null) {
return null;
} else {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(cacheBitmap, 0.0F, 0.0F, (Paint) null);
canvas.save(31);
canvas.restore();
if (!bitmap.isRecycled()) {
LogUtils.verbose("recycle bitmap: " + bitmap.toString());
bitmap.recycle();
}
view.destroyDrawingCache();
view.setWillNotCacheDrawing(willNotCache);
view.setDrawingCacheBackgroundColor(color);
return bitmap;
}
}
public static Drawable toDrawable(Bitmap bitmap) {
return bitmap == null ? null : new BitmapDrawable(Resources.getSystem(), bitmap);
}
public static byte[] toByteArray(Drawable drawable) {
return toByteArray(toBitmap(drawable));
}
public static Drawable toDrawable(byte[] bytes) {
return toDrawable(toBitmap(bytes));
}
public static int toPx(Context context, float dpValue) {
float scale = context.getResources().getDisplayMetrics().density;
int pxValue = (int) (dpValue * scale + 0.5F);
LogUtils.verbose(dpValue + " dp == " + pxValue + " px");
return pxValue;
}
public static int toPx(float dpValue) {
Resources resources = Resources.getSystem();
float px = TypedValue.applyDimension(1, dpValue, resources.getDisplayMetrics());
return (int) px;
}
public static int toDp(Context context, float pxValue) {
float scale = context.getResources().getDisplayMetrics().density;
int dpValue = (int) (pxValue / scale + 0.5F);
LogUtils.verbose(pxValue + " px == " + dpValue + " dp");
return dpValue;
}
public static int toSp(Context context, float pxValue) {
float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
int spValue = (int) (pxValue / fontScale + 0.5F);
LogUtils.verbose(pxValue + " px == " + spValue + " sp");
return spValue;
}
public static String toGbk(String str) {
try {
return new String(str.getBytes("utf-8"), "gbk");
} catch (UnsupportedEncodingException var2) {
LogUtils.warn(var2);
return str;
}
}
public static String toFileSizeString(long fileSize) {
DecimalFormat df = new DecimalFormat("0.00");
String fileSizeString;
if (fileSize < 1024L) {
fileSizeString = fileSize + "B";
} else if (fileSize < 1048576L) {
fileSizeString = df.format((double) fileSize / 1024.0D) + "K";
} else if (fileSize < 1073741824L) {
fileSizeString = df.format((double) fileSize / 1048576.0D) + "M";
} else {
fileSizeString = df.format((double) fileSize / 1.073741824E9D) + "G";
}
return fileSizeString;
}
public static String toString(InputStream is, String charset) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, charset));
while (true) {
String line = reader.readLine();
if (line == null) {
reader.close();
is.close();
break;
}
sb.append(line).append("\n");
}
} catch (IOException var5) {
LogUtils.error(var5);
}
return sb.toString();
}
public static String toString(InputStream is) {
return toString(is, "utf-8");
}
public static int toDarkenColor(@ColorInt int color) {
return toDarkenColor(color, 0.8F);
}
public static int toDarkenColor(@ColorInt int color, @FloatRange(from = 0.0D, to = 1.0D) float value) {
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[2] *= value;
return Color.HSVToColor(hsv);
}
public static String toColorString(@ColorInt int color) {
return toColorString(color, false);
}
public static String toColorString(@ColorInt int color, boolean includeAlpha) {
String alpha = Integer.toHexString(Color.alpha(color));
String red = Integer.toHexString(Color.red(color));
String green = Integer.toHexString(Color.green(color));
String blue = Integer.toHexString(Color.blue(color));
if (alpha.length() == 1) {
alpha = "0" + alpha;
}
if (red.length() == 1) {
red = "0" + red;
}
if (green.length() == 1) {
green = "0" + green;
}
if (blue.length() == 1) {
blue = "0" + blue;
}
String colorString;
if (includeAlpha) {
colorString = alpha + red + green + blue;
LogUtils.verbose(String.format(Locale.CHINA, "%d to color string is %s", new Object[]{
Integer.valueOf(color), colorString}));
} else {
colorString = red + green + blue;
LogUtils.verbose(String.format(Locale.CHINA, "%d to color string is %s%s%s%s, exclude alpha is %s", new Object[]{
Integer.valueOf(color), alpha, red, green, blue, colorString}));
}
return colorString;
}
public static ColorStateList toColorStateList(@ColorInt int normalColor, @ColorInt int pressedColor, @ColorInt int focusedColor, @ColorInt int unableColor) {
int[] colors = new int[]{
pressedColor, focusedColor, normalColor, focusedColor, unableColor, normalColor};
int[][] states = new int[][]{
{
16842919, 16842910}, {
16842910, 16842908}, {
16842910}, {
16842908}, {
16842909}, new int[0]};
return new ColorStateList(states, colors);
}
public static ColorStateList toColorStateList(@ColorInt int normalColor, @ColorInt int pressedColor) {
return toColorStateList(normalColor, pressedColor, pressedColor, normalColor);
}
}
使用方式·Json的处理
Gson gson = new Gson();
String json = ConvertUtils.toString(HomeActivity.this.getAssets().open("room.json"));
RoomBean RoomBeanData = gson.fromJson(json, new TypeToken<RoomBean>() {
}.getType());
room.json 的展示
{
"data": {
"EventInfo": [
{
"HeadPortrait": 0,
"RoomName": "实验室32号楼二楼腰椎穿刺实训中心201",
"State": "已完成",
"StateNumber": 0,
"StudentNumber": "10人",
"SubjectContent": "(1)腰椎穿刺模型模拟实训讲座",
"TeacherName": "李子豪",
"Time": "12:00 - 13:00"
},
{
"HeadPortrait": 1,
"RoomName": "实验室12号楼实训中心212",
"State": "进行中",
"StateNumber": 1,
"StudentNumber": "20人",
"SubjectContent": "(2)心肺复苏考试",
"TeacherName": "杨森",
"Time": "12:10 - 13:30"
},
{
"HeadPortrait": 2,
"RoomName": "实验室31号楼手臂缝合实训中心501",
"State": "等待",
"StateNumber": 2,
"StudentNumber": "21人",
"SubjectContent": "(3)手臂缝合实训讲座",
"TeacherName": "XXX",
"Time": "14:00 - 15:00"
},
{
"HeadPortrait": 3,
"RoomName": "实验室31号楼手臂缝合实训中心501",
"State": "等待",
"StateNumber": 2,
"StudentNumber": "21人",
"SubjectContent": "(3)手臂缝合实训讲座",
"TeacherName": "陶华碧",
"Time": "14:00 - 15:00"
},
{
"HeadPortrait": 4,
"RoomName": "实验室11号楼301",
"State": "等待",
"StateNumber": 2,
"StudentNumber": "33人",
"SubjectContent": "(4)内科手术实训讲座",
"TeacherName": "杨国富",
"Time": "12:30 - 14:00"
},
{
"HeadPortrait": 5,
"RoomName": "实验室1号楼311",
"State": "进行中",
"StateNumber": 1,
"StudentNumber": "30人",
"SubjectContent": "(4)内科手术实训讲座",
"TeacherName": "张科",
"Time": "13:30 - 14:30"
},
{
"HeadPortrait": 6,
"RoomName": "实验室6号楼204",
"State": "等待",
"StateNumber": 2,
"StudentNumber": "10人",
"SubjectContent": "(4)内科手术实训讲座",
"TeacherName": "袁华",
"Time": "13:30 - 14:30"
},
{
"HeadPortrait": 6,
"RoomName": "实验室6号楼204",
"State": "等待",
"StateNumber": 2,
"StudentNumber": "10人",
"SubjectContent": "(4)内科手术实训讲座",
"TeacherName": "袁华",
"Time": "13:30 - 14:30"
}
]
}
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/2829.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...