知道这些公用类,让你少写10000行代码(持续更新)

作为一枚Android开发人员,如果能汇总一些公用类,对我们平时的开发效率会有很大的帮助。

这样我们能抽出更多的时间,该研究新技术的研究技术,这样离升职加薪就不远了。

该抱妹子就抱妹子,这样美好的爱情指日可待。

生活有时没必要那么苟且,也应有诗和远方,如果现在还没妹子,不妨看看我的另一篇文章,《我愿意嫁给程序员》评论够精彩,相信对你找妹子有很大的帮助。强调一下,不是叫你看文章内容,评论,评论,评论,重要的事要说三遍。

今天起,开始整理汇总一些关于Android开发开源公用类分享给大家,谢谢对大家学习有帮助,提高工作效率。

今天是分享一个转换类 ConvertUtils.java

该类目录结构

bytes2HexString, hexString2Bytes         : byteArr与hexString互转
chars2Bytes, bytes2Chars                 : charArr与byteArr互转
byte2Size, size2Byte                     : 字节数与unit为单位的size互转
byte2FitSize                             : 字节数转合适大小
bytes2Bits, bits2Bytes                   : bytes与bits互转
input2OutputStream, output2InputStream   : inputStream与outputStream互转
inputStream2Bytes, bytes2InputStream     : inputStream与byteArr互转
outputStream2Bytes, bytes2OutputStream   : outputStream与byteArr互转
inputStream2String, string2InputStream   : inputStream与string按编码互转
outputStream2String, string2OutputStream : outputStream与string按编码互转
bitmap2Bytes, bytes2Bitmap               : bitmap与byteArr互转
drawable2Bitmap, bitmap2Drawable         : drawable与bitmap互转
drawable2Bytes, bytes2Drawable           : drawable与byteArr互转
view2Bitmap                              : view转Bitmap
dp2px, px2dp                             : dp与px互转
sp2px, px2sp                             : sp与px互转
import android.annotation.SuppressLint;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

/**
*  转换相关工具类
*/
public class ConvertUtils {

   private ConvertUtils() {
       throw new UnsupportedOperationException("u can't instantiate me...");
   }

   private static final char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

   /**
    * byteArr转hexString
    * <p>例如:</p>
    * bytes2HexString(new byte[] { 0, (byte) 0xa8 }) returns 00A8
    *
    * @param bytes 字节数组
    * @return 16进制大写字符串
    */
   public static String bytes2HexString(byte[] bytes) {
       if (bytes == null) return null;
       int len = bytes.length;
       if (len <= 0) return null;
       char[] ret = new char[len << 1];
       for (int i = 0, j = 0; i < len; i++) {
           ret[j++] = hexDigits[bytes[i] >>> 4 & 0x0f];
           ret[j++] = hexDigits[bytes[i] & 0x0f];
       }
       return new String(ret);
   }

   /**
    * hexString转byteArr
    * <p>例如:</p>
    * hexString2Bytes("00A8") returns { 0, (byte) 0xA8 }
    *
    * @param hexString 十六进制字符串
    * @return 字节数组
    */
   public static byte[] hexString2Bytes(String hexString) {
       if (StringUtils.isSpace(hexString)) return null;
       int len = hexString.length();
       if (len % 2 != 0) {
           hexString = "0" + hexString;
           len = len + 1;
       }
       char[] hexBytes = hexString.toUpperCase().toCharArray();
       byte[] ret = new byte[len >> 1];
       for (int i = 0; i < len; i += 2) {
           ret[i >> 1] = (byte) (hex2Dec(hexBytes[i]) << 4 | hex2Dec(hexBytes[i + 1]));
       }
       return ret;
   }

   /**
    * hexChar转int
    *
    * @param hexChar hex单个字节
    * @return 0..15
    */
   private static int hex2Dec(char hexChar) {
       if (hexChar >= '0' && hexChar <= '9') {
           return hexChar - '0';
       } else if (hexChar >= 'A' && hexChar <= 'F') {
           return hexChar - 'A' + 10;
       } else {
           throw new IllegalArgumentException();
       }
   }

   /**
    * charArr转byteArr
    *
    * @param chars 字符数组
    * @return 字节数组
    */
   public static byte[] chars2Bytes(char[] chars) {
       if (chars == null || chars.length <= 0) return null;
       int len = chars.length;
       byte[] bytes = new byte[len];
       for (int i = 0; i < len; i++) {
           bytes[i] = (byte) (chars[i]);
       }
       return bytes;
   }

   /**
    * byteArr转charArr
    *
    * @param bytes 字节数组
    * @return 字符数组
    */
   public static char[] bytes2Chars(byte[] bytes) {
       if (bytes == null) return null;
       int len = bytes.length;
       if (len <= 0) return null;
       char[] chars = new char[len];
       for (int i = 0; i < len; i++) {
           chars[i] = (char) (bytes[i] & 0xff);
       }
       return chars;
   }

   /**
    * 以unit为单位的内存大小转字节数
    *
    * @param memorySize 大小
    * @param unit       单位类型
    *                   <ul>
    *                   <li>{@link ConstUtils.MemoryUnit#BYTE}: 字节</li>
    *                   <li>{@link ConstUtils.MemoryUnit#KB}  : 千字节</li>
    *                   <li>{@link ConstUtils.MemoryUnit#MB}  : 兆</li>
    *                   <li>{@link ConstUtils.MemoryUnit#GB}  : GB</li>
    *                   </ul>
    * @return 字节数
    */
   public static long memorySize2Byte(long memorySize, ConstUtils.MemoryUnit unit) {
       if (memorySize < 0) return -1;
       switch (unit) {
           default:
           case BYTE:
               return memorySize;
           case KB:
               return memorySize * ConstUtils.KB;
           case MB:
               return memorySize * ConstUtils.MB;
           case GB:
               return memorySize * ConstUtils.GB;
       }
   }

   /**
    * 字节数转以unit为单位的内存大小
    *
    * @param byteNum 字节数
    * @param unit    单位类型
    *                <ul>
    *                <li>{@link ConstUtils.MemoryUnit#BYTE}: 字节</li>
    *                <li>{@link ConstUtils.MemoryUnit#KB}  : 千字节</li>
    *                <li>{@link ConstUtils.MemoryUnit#MB}  : 兆</li>
    *                <li>{@link ConstUtils.MemoryUnit#GB}  : GB</li>
    *                </ul>
    * @return 以unit为单位的size
    */
   public static double byte2MemorySize(long byteNum, ConstUtils.MemoryUnit unit) {
       if (byteNum < 0) return -1;
       switch (unit) {
           default:
           case BYTE:
               return (double) byteNum;
           case KB:
               return (double) byteNum / ConstUtils.KB;
           case MB:
               return (double) byteNum / ConstUtils.MB;
           case GB:
               return (double) byteNum / ConstUtils.GB;
       }
   }

   /**
    * 字节数转合适内存大小
    * <p>保留3位小数</p>
    *
    * @param byteNum 字节数
    * @return 合适内存大小
    */
   @SuppressLint("DefaultLocale")
   public static String byte2FitMemorySize(long byteNum) {
       if (byteNum < 0) {
           return "shouldn't be less than zero!";
       } else if (byteNum < ConstUtils.KB) {
           return String.format("%.3fB", byteNum + 0.0005);
       } else if (byteNum < ConstUtils.MB) {
           return String.format("%.3fKB", byteNum / ConstUtils.KB + 0.0005);
       } else if (byteNum < ConstUtils.GB) {
           return String.format("%.3fMB", byteNum / ConstUtils.MB + 0.0005);
       } else {
           return String.format("%.3fGB", byteNum / ConstUtils.GB + 0.0005);
       }
   }

   /**
    * 以unit为单位的时间长度转毫秒时间戳
    *
    * @param timeSpan 毫秒时间戳
    * @param unit     单位类型
    *                 <ul>
    *                 <li>{@link ConstUtils.TimeUnit#MSEC}: 毫秒</li>
    *                 <li>{@link ConstUtils.TimeUnit#SEC }: 秒</li>
    *                 <li>{@link ConstUtils.TimeUnit#MIN }: 分</li>
    *                 <li>{@link ConstUtils.TimeUnit#HOUR}: 小时</li>
    *                 <li>{@link ConstUtils.TimeUnit#DAY }: 天</li>
    *                 </ul>
    * @return 毫秒时间戳
    */
   public static long timeSpan2Millis(long timeSpan, ConstUtils.TimeUnit unit) {
       switch (unit) {
           default:
           case MSEC:
               return timeSpan;
           case SEC:
               return timeSpan * ConstUtils.SEC;
           case MIN:
               return timeSpan * ConstUtils.MIN;
           case HOUR:
               return timeSpan * ConstUtils.HOUR;
           case DAY:
               return timeSpan * ConstUtils.DAY;
       }
   }

   /**
    * 毫秒时间戳转以unit为单位的时间长度
    *
    * @param millis 毫秒时间戳
    * @param unit   单位类型
    *               <ul>
    *               <li>{@link ConstUtils.TimeUnit#MSEC}: 毫秒</li>
    *               <li>{@link ConstUtils.TimeUnit#SEC }: 秒</li>
    *               <li>{@link ConstUtils.TimeUnit#MIN }: 分</li>
    *               <li>{@link ConstUtils.TimeUnit#HOUR}: 小时</li>
    *               <li>{@link ConstUtils.TimeUnit#DAY }: 天</li>
    *               </ul>
    * @return 以unit为单位的时间长度
    */
   public static long millis2TimeSpan(long millis, ConstUtils.TimeUnit unit) {
       switch (unit) {
           default:
           case MSEC:
               return millis;
           case SEC:
               return millis / ConstUtils.SEC;
           case MIN:
               return millis / ConstUtils.MIN;
           case HOUR:
               return millis / ConstUtils.HOUR;
           case DAY:
               return millis / ConstUtils.DAY;
       }
   }

   /**
    * 毫秒时间戳转合适时间长度
    *
    * @param millis    毫秒时间戳
    *                  <p>小于等于0,返回null</p>
    * @param precision 精度
    *                  <p>precision = 0,返回null</p>
    *                  <p>precision = 1,返回天</p>
    *                  <p>precision = 2,返回天和小时</p>
    *                  <p>precision = 3,返回天、小时和分钟</p>
    *                  <p>precision = 4,返回天、小时、分钟和秒</p>
    *                  <p>precision >= 5,返回天、小时、分钟、秒和毫秒</p>
    * @return 合适时间长度
    */
   @SuppressLint("DefaultLocale")
   public static String millis2FitTimeSpan(long millis, int precision) {
       if (millis <= 0 || precision <= 0) return null;
       StringBuilder sb = new StringBuilder();
       String[] units = {"天", "小时", "分钟", "秒", "毫秒"};
       int[] unitLen = {86400000, 3600000, 60000, 1000, 1};
       precision = Math.min(precision, 5);
       for (int i = 0; i < precision; i++) {
           if (millis >= unitLen[i]) {
               long mode = millis / unitLen[i];
               millis -= mode * unitLen[i];
               sb.append(mode).append(units[i]);
           }
       }
       return sb.toString();
   }

   /**
    * bytes转bits
    *
    * @param bytes 字节数组
    * @return bits
    */
   public static String bytes2Bits(byte[] bytes) {
       StringBuilder sb = new StringBuilder();
       for (byte aByte : bytes) {
           for (int j = 7; j >= 0; --j) {
               sb.append(((aByte >> j) & 0x01) == 0 ? '0' : '1');
           }
       }
       return sb.toString();
   }

   /**
    * bits转bytes
    *
    * @param bits 二进制
    * @return bytes
    */
   public static byte[] bits2Bytes(String bits) {
       int lenMod = bits.length() % 8;
       int byteLen = bits.length() / 8;
       // 不是8的倍数前面补0
       if (lenMod != 0) {
           for (int i = lenMod; i < 8; i++) {
               bits = "0" + bits;
           }
           byteLen++;
       }
       byte[] bytes = new byte[byteLen];
       for (int i = 0; i < byteLen; ++i) {
           for (int j = 0; j < 8; ++j) {
               bytes[i] <<= 1;
               bytes[i] |= bits.charAt(i * 8 + j) - '0';
           }
       }
       return bytes;
   }

   /**
    * inputStream转outputStream
    *
    * @param is 输入流
    * @return outputStream子类
    */
   public static ByteArrayOutputStream input2OutputStream(InputStream is) {
       if (is == null) return null;
       try {
           ByteArrayOutputStream os = new ByteArrayOutputStream();
           byte[] b = new byte[ConstUtils.KB];
           int len;
           while ((len = is.read(b, 0, ConstUtils.KB)) != -1) {
               os.write(b, 0, len);
           }
           return os;
       } catch (IOException e) {
           e.printStackTrace();
           return null;
       } finally {
           CloseUtils.closeIO(is);
       }
   }

   /**
    * outputStream转inputStream
    *
    * @param out 输出流
    * @return inputStream子类
    */
   public ByteArrayInputStream output2InputStream(OutputStream out) {
       if (out == null) return null;
       return new ByteArrayInputStream(((ByteArrayOutputStream) out).toByteArray());
   }

   /**
    * inputStream转byteArr
    *
    * @param is 输入流
    * @return 字节数组
    */
   public static byte[] inputStream2Bytes(InputStream is) {
       if (is == null) return null;
       return input2OutputStream(is).toByteArray();
   }

   /**
    * byteArr转inputStream
    *
    * @param bytes 字节数组
    * @return 输入流
    */
   public static InputStream bytes2InputStream(byte[] bytes) {
       if (bytes == null || bytes.length <= 0) return null;
       return new ByteArrayInputStream(bytes);
   }

   /**
    * outputStream转byteArr
    *
    * @param out 输出流
    * @return 字节数组
    */
   public static byte[] outputStream2Bytes(OutputStream out) {
       if (out == null) return null;
       return ((ByteArrayOutputStream) out).toByteArray();
   }

   /**
    * outputStream转byteArr
    *
    * @param bytes 字节数组
    * @return 字节数组
    */
   public static OutputStream bytes2OutputStream(byte[] bytes) {
       if (bytes == null || bytes.length <= 0) return null;
       ByteArrayOutputStream os = null;
       try {
           os = new ByteArrayOutputStream();
           os.write(bytes);
           return os;
       } catch (IOException e) {
           e.printStackTrace();
           return null;
       } finally {
           CloseUtils.closeIO(os);
       }
   }

   /**
    * inputStream转string按编码
    *
    * @param is          输入流
    * @param charsetName 编码格式
    * @return 字符串
    */
   public static String inputStream2String(InputStream is, String charsetName) {
       if (is == null || StringUtils.isSpace(charsetName)) return null;
       try {
           return new String(inputStream2Bytes(is), charsetName);
       } catch (UnsupportedEncodingException e) {
           e.printStackTrace();
           return null;
       }
   }

   /**
    * string转inputStream按编码
    *
    * @param string      字符串
    * @param charsetName 编码格式
    * @return 输入流
    */
   public static InputStream string2InputStream(String string, String charsetName) {
       if (string == null || StringUtils.isSpace(charsetName)) return null;
       try {
           return new ByteArrayInputStream(string.getBytes(charsetName));
       } catch (UnsupportedEncodingException e) {
           e.printStackTrace();
           return null;
       }
   }

   /**
    * outputStream转string按编码
    *
    * @param out         输出流
    * @param charsetName 编码格式
    * @return 字符串
    */
   public static String outputStream2String(OutputStream out, String charsetName) {
       if (out == null || StringUtils.isSpace(charsetName)) return null;
       try {
           return new String(outputStream2Bytes(out), charsetName);
       } catch (UnsupportedEncodingException e) {
           e.printStackTrace();
           return null;
       }
   }

   /**
    * string转outputStream按编码
    *
    * @param string      字符串
    * @param charsetName 编码格式
    * @return 输入流
    */
   public static OutputStream string2OutputStream(String string, String charsetName) {
       if (string == null || StringUtils.isSpace(charsetName)) return null;
       try {
           return bytes2OutputStream(string.getBytes(charsetName));
       } catch (UnsupportedEncodingException e) {
           e.printStackTrace();
           return null;
       }
   }

   /**
    * bitmap转byteArr
    *
    * @param bitmap bitmap对象
    * @param format 格式
    * @return 字节数组
    */
   public static byte[] bitmap2Bytes(Bitmap bitmap, Bitmap.CompressFormat format) {
       if (bitmap == null) return null;
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       bitmap.compress(format, 100, baos);
       return baos.toByteArray();
   }

   /**
    * byteArr转bitmap
    *
    * @param bytes 字节数组
    * @return bitmap
    */
   public static Bitmap bytes2Bitmap(byte[] bytes) {
       return (bytes == null || bytes.length == 0) ? null : BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
   }

   /**
    * drawable转bitmap
    *
    * @param drawable drawable对象
    * @return bitmap
    */
   public static Bitmap drawable2Bitmap(Drawable drawable) {
       return drawable == null ? null : ((BitmapDrawable) drawable).getBitmap();
   }

   /**
    * bitmap转drawable
    *
    * @param res    resources对象
    * @param bitmap bitmap对象
    * @return drawable
    */
   public static Drawable bitmap2Drawable(Resources res, Bitmap bitmap) {
       return bitmap == null ? null : new BitmapDrawable(res, bitmap);
   }

   /**
    * drawable转byteArr
    *
    * @param drawable drawable对象
    * @param format   格式
    * @return 字节数组
    */
   public static byte[] drawable2Bytes(Drawable drawable, Bitmap.CompressFormat format) {
       return drawable == null ? null : bitmap2Bytes(drawable2Bitmap(drawable), format);
   }

   /**
    * byteArr转drawable
    *
    * @param res   resources对象
    * @param bytes 字节数组
    * @return drawable
    */
   public static Drawable bytes2Drawable(Resources res, byte[] bytes) {
       return res == null ? null : bitmap2Drawable(res, bytes2Bitmap(bytes));
   }

   /**
    * view转Bitmap
    *
    * @param view 视图
    * @return bitmap
    */
   public static Bitmap view2Bitmap(View view) {
       if (view == null) return null;
       Bitmap ret = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
       Canvas canvas = new Canvas(ret);
       Drawable bgDrawable = view.getBackground();
       if (bgDrawable != null) {
           bgDrawable.draw(canvas);
       } else {
           canvas.drawColor(Color.WHITE);
       }
       view.draw(canvas);
       return ret;
   }

   /**
    * dp转px
    *
    * @param dpValue dp值
    * @return px值
    */
   public static int dp2px(float dpValue) {
       final float scale = Utils.context.getResources().getDisplayMetrics().density;
       return (int) (dpValue * scale + 0.5f);
   }

   /**
    * px转dp
    *
    * @param pxValue px值
    * @return dp值
    */
   public static int px2dp(float pxValue) {
       final float scale = Utils.context.getResources().getDisplayMetrics().density;
       return (int) (pxValue / scale + 0.5f);
   }

   /**
    * sp转px
    *
    * @param spValue sp值
    * @return px值
    */
   public static int sp2px(float spValue) {
       final float fontScale = Utils.context.getResources().getDisplayMetrics().scaledDensity;
       return (int) (spValue * fontScale + 0.5f);
   }

   /**
    * px转sp
    *
    * @param pxValue px值
    * @return sp值
    */
   public static int px2sp(float pxValue) {
       final float fontScale = Utils.context.getResources().getDisplayMetrics().scaledDensity;
       return (int) (pxValue / fontScale + 0.5f);
   }
}

该类来源
https://github.com/Blankj/AndroidUtilCode/blob/master/utilcode/src/main/java/com/blankj/utilcode/utils/ConvertUtils.java
不用谢我,我只是一名搬运工。感谢原作者的开源。

祝你在新的一年里,新年新气象,一切都好!

[END]

我是洪生鹏,热衷旅行、写作,目前过着白天到工地搬砖、晚上写故事的生活。希望今天的文章对你有帮助。

如果你喜欢今天的文章,猜你喜欢
程序员月薪多少才不会焦虑
为什么有的人工作多年还是老样子
怕出丑,只怕会错过更大的收获
如何优雅的赞美他人?答案在这里
孤独,是年青人最好的修行

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

推荐阅读更多精彩内容