android 下載音頻到本地并獲取路徑播放

@[TOC](文章目錄)

# 一航邢、寫DownloadAudio下載工具類

```java

import android.annotation.SuppressLint;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.List;

import okhttp3.Call;

import okhttp3.Callback;

import okhttp3.OkHttpClient;

import okhttp3.Request;

import okhttp3.Response;

/**

* @author : Code23

* @time : 2020/11/5

* @module : DownloadAudio

* @describe :

*/

public class DownloadAudio {

? ? private File file;

? ? public String savePath; // 儲存下載文件的路徑

? ? private List<String> audiolist = new ArrayList<>();//獲取接口的數(shù)據(jù)

? ? private List<String> audioNamelist = new ArrayList<>();//獲取本地已下載的文件名

? ? public DownloadAudioListener downloadAudioListener;

? ? public DownloadAudio(DownloadAudioListener downloadAudioListener, String savePath, List<String> audiolist) {

? ? ? ? this.downloadAudioListener = downloadAudioListener;

? ? ? ? this.savePath = savePath;

? ? ? ? this.audiolist = audiolist;

? ? ? ? audioNamelist.clear();

? ? ? ? audioNamelist = getFilesAllName(savePath);//獲取本地已下載的文件名

? ? }

/**

? ? *@author : Code23

? ? *@time : 2020/11/12

? ? *@name : isDownloadAudio

? ? *@Parameters : [url, i]

? ? *@describe : 判斷是否已經(jīng)下載過,已經(jīng)下載的返回路徑渤刃,沒下載的繼續(xù)下載

? ? */

? ? public void isDownloadAudio(final String url, final int i) {

? ? ? ? if (audioNamelist != null) {

? ? ? ? ? ? if (audioNamelist.size() > 0) {

? ? ? ? ? ? ? ? for (int t = 0; t < audioNamelist.size(); t++) {

? ? ? ? ? ? ? ? ? ? if (audiolist.get(i).equals(audioNamelist.get(t))) {

? ? ? ? ? ? ? ? ? ? ? ? downloadAudioListener.DownloadSuccess(savePath + "/" + audioNamelist.get(i), i);

? ? ? ? ? ? ? ? ? ? ? ? break;

? ? ? ? ? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? ? ? ? ? if (t == audiolist.size() - 1) {

? ? ? ? ? ? ? ? ? ? ? ? ? ? OkHttpDownloadAudio(url, i);

? ? ? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? }

? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? OkHttpDownloadAudio(url, i);

? ? ? ? ? ? }

? ? ? ? } else {

? ? ? ? ? ? OkHttpDownloadAudio(url, i);

? ? ? ? }

? ? }

? ? /**

? ? * @author : Code23

? ? * @time : 2020/11/5

? ? * @name : downloadFile

? ? * @Parameters : [url, name, dowloadpath]

? ? * @describe :下載文件

? ? */

? ? @SuppressLint("NewApi")

? ? public void OkHttpDownloadAudio(final String url, final int i) {

? ? ? ? OkHttpClient okHttpClient = new OkHttpClient();

? ? ? ? Request request = new Request.Builder().url(url).build();

? ? ? ? okHttpClient.newCall(request).enqueue(new Callback() {

? ? ? ? ? ? @Override

? ? ? ? ? ? public void onFailure(Call call, IOException e) {

? ? ? ? ? ? ? ? //請求失敗

? ? ? ? ? ? ? ? downloadAudioListener.DownloadFailure("failure", i);

? ? ? ? ? ? }

? ? ? ? ? ? @Override

? ? ? ? ? ? public void onResponse(Call call, Response response) throws IOException {

? ? ? ? ? ? ? ? //請求成功

? ? ? ? ? ? ? ? InputStream inputStream = null;

? ? ? ? ? ? ? ? FileOutputStream fileOutputStream = null;

? ? ? ? ? ? ? ? byte[] bytes = new byte[1024 * 10];

? ? ? ? ? ? ? ? int length = 0;

? ? ? ? ? ? ? ? file = new File(savePath);

? ? ? ? ? ? ? ? if (!file.exists()) { //文件夾不存在

? ? ? ? ? ? ? ? ? ? // 創(chuàng)建文件夾

? ? ? ? ? ? ? ? ? ? file.mkdirs();

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? try {

? ? ? ? ? ? ? ? ? ? inputStream = response.body().byteStream();

? ? ? ? ? ? ? ? ? ? file = new File(savePath, audiolist.get(i));

? ? ? ? ? ? ? ? ? ? fileOutputStream = new FileOutputStream(file);

? ? ? ? ? ? ? ? ? ? while ((length = inputStream.read(bytes)) != -1) {

? ? ? ? ? ? ? ? ? ? ? ? fileOutputStream.write(bytes, 0, length);

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ? ? fileOutputStream.flush();

? ? ? ? ? ? ? ? ? ? //下載成功

? ? ? ? ? ? ? ? ? ? downloadAudioListener.DownloadSuccess(file.getPath(), i);

? ? ? ? ? ? ? ? } catch (Exception e) {

? ? ? ? ? ? ? ? ? ? e.printStackTrace();

? ? ? ? ? ? ? ? ? ? // 下載失敗

? ? ? ? ? ? ? ? ? ? downloadAudioListener.DownloadFailure("failure", i);

? ? ? ? ? ? ? ? } finally {

? ? ? ? ? ? ? ? ? ? if (inputStream != null) {

? ? ? ? ? ? ? ? ? ? ? ? inputStream.close();

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ? ? if (fileOutputStream != null) {

? ? ? ? ? ? ? ? ? ? ? ? fileOutputStream.close();

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? });

? ? }

? ? public interface DownloadAudioListener {

? ? ? ? void DownloadSuccess(String audiourl, int i);//成功返回

? ? ? ? void DownloadFailure(String audiourl, int i);//失敗返回

? ? }

? ? /**

? ? * 獲取文件夾所有文件名

? ? *

? ? * @param path

? ? * @return

? ? */

? ? public List<String> getFilesAllName(String path) {

? ? ? ? File file = new File(path);

? ? ? ? if (!file.exists()) { //文件夾不存在

? ? ? ? ? ? // 創(chuàng)建文件夾

? ? ? ? ? ? file.mkdirs();

? ? ? ? }

? ? ? ? File[] files = file.listFiles();

? ? ? ? if (files == null) {//空目錄

? ? ? ? ? ? return null;

? ? ? ? }

? ? ? ? List<String> stringList = new ArrayList<>();

? ? ? ? for (int i = 0; i < files.length; i++) {

? ? ? ? ? ? stringList.add(files[i].getName());

? ? ? ? }

? ? ? ? return stringList;

? ? }

}

```

# 二皱碘、在Activity或者其他地方使用DownloadAudio工具類

<font color=#999AAA >代碼如下(示例):

```java

import android.app.Activity;

import android.media.AudioManager;

import android.media.MediaPlayer;

import android.os.Bundle;

import android.os.Environment;

import android.os.Handler;

import android.support.annotation.Nullable;

import com.colortu.listening.constant.Urls;

import com.colortu.listening.utils.DownloadAudio;

import com.colortu.listening.utils.string.StringUtil;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;

/**

* @author : Code23

* @time : 2020/11/12

* @module : D

* @describe :

*/

public class AudioPlayerActivity extends Activity implements DownloadAudio.DownloadAudioListener{

? ? private MediaPlayer mediaPlayer;

? ? private Handler handler;

? ? private List<String> demolist = new ArrayList<>();//你獲取的網(wǎng)絡(luò)數(shù)據(jù)

? ? private DownloadAudio downloadAudio;

? ? private List<String> audiolist = new ArrayList<>();

? ? private String[] audionamelist;

? ? @Override

? ? protected void onCreate(@Nullable Bundle savedInstanceState) {

? ? ? ? super.onCreate(savedInstanceState);

? ? ? ? initView();

? ? }

? ? private void initView(){

? ? ? ? handler = new Handler();

? ? ? ? String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Demo";

? ? ? ? for (int i = 0; i < demolist.size(); i++) {

? ? ? ? ? ? audiolist.add(StringUtil.makeMd5(Urls.CDN_URL + demolist.get(i)));//將網(wǎng)絡(luò)下載url轉(zhuǎn)成md5

? ? ? ? }

? ? ? ? audionamelist = new String[demolist.size()];

? ? ? ? downloadAudio = new DownloadAudio(this, savePath, audiolist);

? ? ? ? //將下載的url轉(zhuǎn)成MD5,下載的文件名為MD5宙项。首次進(jìn)來拿本地下載好的文件名和網(wǎng)絡(luò)拿下來的數(shù)據(jù)對比娃属,

? ? ? ? //沒有的就下載,有的就返回文件路徑就行

? ? ? ? if(demolist.size()>0){

? ? ? ? ? ? downloadAudio.isDownloadAudio(Urls.CDN_URL + demolist.get(0), 0);

? ? ? ? }

? ? ? ? //可以設(shè)置加載動畫蛉顽,下載完后調(diào)用play()

? ? ? ? play();

? ? }

? ? private void play(){

? ? ? ? handler.removeCallbacks(playAudioRun);

? ? ? ? handler.post(playAudioRun);

? ? }

? ? private int curItem;//自己去拿你的播放哪一個的下標(biāo)

? ? Runnable playAudioRun = new Runnable() {

? ? ? ? @Override

? ? ? ? public void run() {

? ? ? ? ? ? if (audionamelist != null) {

? ? ? ? ? ? ? ? if (audionamelist[curItem] != null) {

? ? ? ? ? ? ? ? ? ? if (!audionamelist[curItem].equals("failure") && !audionamelist[curItem].equals("")) {

? ? ? ? ? ? ? ? ? ? ? ? playAudio(audionamelist[curItem]);//播放本地路徑

? ? ? ? ? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? ? ? ? ? playAudio( demolist.get(curItem));//下載失敗或者本地找不到路徑就網(wǎng)絡(luò)播放

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? ? ? playAudio(demolist.get(curItem));//下載失敗或者本地找不到路徑就網(wǎng)絡(luò)播放

? ? ? ? ? ? ? ? }

? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? playAudio(demolist.get(curItem));//下載失敗或者本地找不到路徑就網(wǎng)絡(luò)播放

? ? ? ? ? ? }

? ? ? ? }

? ? };

? ? private void playAudio(String url) {

? ? ? ? mediaPlayer = new MediaPlayer();

? ? ? ? try {

? ? ? ? ? ? mediaPlayer.setDataSource(url);

? ? ? ? ? ? mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

? ? ? ? } catch (IOException e) {

? ? ? ? ? ? e.printStackTrace();

? ? ? ? }

? ? ? ? if (mediaPlayer == null) {

? ? ? ? ? ? return;

? ? ? ? }

? ? ? ? mediaPlayer.setLooping(false);

? ? ? ? mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

? ? ? ? ? ? @Override

? ? ? ? ? ? public void onCompletion(MediaPlayer mp) {

? ? ? ? ? ? ? ? mediaPlayer.stop();

? ? ? ? ? ? ? ? mediaPlayer.reset();

? ? ? ? ? ? }

? ? ? ? });

? ? ? ? mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

? ? ? ? ? ? @Override

? ? ? ? ? ? public void onPrepared(MediaPlayer mp) {

? ? ? ? ? ? ? ? if (mediaPlayer == mp) {

? ? ? ? ? ? ? ? ? ? mediaPlayer.start();

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? });

? ? ? ? mediaPlayer.prepareAsync();

? ? }

? ? @Override

? ? public void DownloadSuccess(String audiourl, int i) {

? ? ? ? if (i < demolist.size()) {

? ? ? ? ? ? audionamelist[i] = audiourl;

? ? ? ? ? ? i++;

? ? ? ? ? ? if (i < demolist.size()) {

? ? ? ? ? ? ? ? downloadAudio.isDownloadAudio(demolist.get(i), i);

? ? ? ? ? ? }

? ? ? ? }

? ? }

? ? @Override

? ? public void DownloadFailure(String audiourl, int i) {

? ? ? ? if (i < demolist.size()) {

? ? ? ? ? ? audionamelist[i] = audiourl;

? ? ? ? ? ? i++;

? ? ? ? ? ? if (i < demolist.size()) {

? ? ? ? ? ? ? ? downloadAudio.isDownloadAudio(demolist.get(i), i);

? ? ? ? ? ? }

? ? ? ? }

? ? }

}

```

# 三蝗砾、String轉(zhuǎn)MD5工具類

## 1.StringUtil 類

```java

import android.text.TextUtils;

import java.util.Locale;

import java.util.UUID;

public class StringUtil {

/**

? ? * String轉(zhuǎn)md5

? ? *

? ? * @param source

? ? * @return String

? ? */

? public static String makeMd5(String source) {

? ? ? ? return MD5.getStringMD5(source);

? ? }

? ? /**

? ? * 刪除字符串中的空白符

? ? *

? ? * @param content

? ? * @return String

? ? */

? ? public static String removeBlanks(String content) {

? ? ? ? if (content == null) {

? ? ? ? ? ? return null;

? ? ? ? }

? ? ? ? StringBuilder buff = new StringBuilder();

? ? ? ? buff.append(content);

? ? ? ? for (int i = buff.length() - 1; i >= 0; i--) {

? ? ? ? ? ? if (' ' == buff.charAt(i) || ('\n' == buff.charAt(i)) || ('\t' == buff.charAt(i))

? ? ? ? ? ? ? ? ? ? || ('\r' == buff.charAt(i))) {

? ? ? ? ? ? ? ? buff.deleteCharAt(i);

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? return buff.toString();

? ? }

? ? /**

? ? * 獲取32位uuid

? ? *

? ? * @return

? ? */

? ? public static String get32UUID() {

? ? ? ? return UUID.randomUUID().toString().replaceAll("-", "");

? ? }

? ? public static boolean isEmpty(String input) {

? ? ? ? return TextUtils.isEmpty(input);

? ? }

? ? /**

? ? * 生成唯一號

? ? *

? ? * @return

? ? */

? ? public static String get36UUID() {

? ? ? ? UUID uuid = UUID.randomUUID();

? ? ? ? String uniqueId = uuid.toString();

? ? ? ? return uniqueId;

? ? }

? ? public static final String filterUCS4(String str) {

? ? ? ? if (TextUtils.isEmpty(str)) {

? ? ? ? ? ? return str;

? ? ? ? }

? ? ? ? if (str.codePointCount(0, str.length()) == str.length()) {

? ? ? ? ? ? return str;

? ? ? ? }

? ? ? ? StringBuilder sb = new StringBuilder();

? ? ? ? int index = 0;

? ? ? ? while (index < str.length()) {

? ? ? ? ? ? int codePoint = str.codePointAt(index);

? ? ? ? ? ? index += Character.charCount(codePoint);

? ? ? ? ? ? if (Character.isSupplementaryCodePoint(codePoint)) {

? ? ? ? ? ? ? ? continue;

? ? ? ? ? ? }

? ? ? ? ? ? sb.appendCodePoint(codePoint);

? ? ? ? }

? ? ? ? return sb.toString();

? ? }

? ? /**

? ? * counter ASCII character as one, otherwise two

? ? *

? ? * @param str

? ? * @return count

? ? */

? ? public static int counterChars(String str) {

? ? ? ? // return

? ? ? ? if (TextUtils.isEmpty(str)) {

? ? ? ? ? ? return 0;

? ? ? ? }

? ? ? ? int count = 0;

? ? ? ? for (int i = 0; i < str.length(); i++) {

? ? ? ? ? ? int tmp = (int) str.charAt(i);

? ? ? ? ? ? if (tmp > 0 && tmp < 127) {

? ? ? ? ? ? ? ? count += 1;

? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? count += 2;

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? return count;

? ? }

}

```

## 2.MD5 類

```java

import java.io.BufferedInputStream;

import java.io.FileInputStream;

import java.io.UnsupportedEncodingException;

import java.security.MessageDigest;

public class MD5 {

? ? public static String getStringMD5(String value) {

? ? ? ? if (value == null || value.trim().length() < 1) {

? ? ? ? ? ? return null;

? ? ? ? }

? ? ? ? try {

? ? ? ? ? ? return getMD5(value.getBytes("UTF-8"));

? ? ? ? } catch (UnsupportedEncodingException e) {

? ? ? ? ? ? throw new RuntimeException(e.getMessage(), e);

? ? ? ? }

? ? }

? ? public static String getMD5(byte[] source) {

? ? ? ? try {

? ? ? ? ? ? MessageDigest md5 = MessageDigest.getInstance("MD5");

? ? ? ? ? ? return HexDump.toHex(md5.digest(source));

? ? ? ? } catch (Exception e) {

? ? ? ? ? ? throw new RuntimeException(e.getMessage(), e);

? ? ? ? }

? ? }

? ? public static String getStreamMD5(String filePath) {

? ? ? ? String hash = null;

? ? ? ? byte[] buffer = new byte[4096];

? ? ? ? BufferedInputStream in = null;

? ? ? ? try {

? ? ? ? ? ? MessageDigest md5 = MessageDigest.getInstance("MD5");

? ? ? ? ? ? in = new BufferedInputStream(new FileInputStream(filePath));

? ? ? ? ? ? int numRead = 0;

? ? ? ? ? ? while ((numRead = in.read(buffer)) > 0) {

? ? ? ? ? ? ? ? md5.update(buffer, 0, numRead);

? ? ? ? ? ? }

? ? ? ? ? ? in.close();

? ? ? ? ? ? hash = HexDump.toHex(md5.digest());

? ? ? ? } catch (Exception e) {

? ? ? ? ? ? e.printStackTrace();

? ? ? ? } finally {

? ? ? ? ? ? if (in != null) {

? ? ? ? ? ? ? ? try {

? ? ? ? ? ? ? ? ? ? in.close();

? ? ? ? ? ? ? ? } catch (Exception ex) {

? ? ? ? ? ? ? ? ? ? ex.printStackTrace();

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? return hash;

? ? }

}

```

## 3.HexDump? 類

```java

import java.io.IOException;

import java.io.StringReader;

public class HexDump {

? ? class HexTablifier {

? ? ? ? private int m_row = 8;

? ? ? ? private String m_pre = "";

? ? ? ? private String m_post = "\n";

? ? ? ? public HexTablifier() {

? ? ? ? }

? ? ? ? public HexTablifier(int row) {

? ? ? ? ? ? this(row, "", "\n");

? ? ? ? }

? ? ? ? public HexTablifier(int row, String pre) {

? ? ? ? ? ? this(row, pre, "\n");

? ? ? ? }

? ? ? ? public HexTablifier(int row, String pre, String post) {

? ? ? ? ? ? m_row = row;

? ? ? ? ? ? m_pre = pre;

? ? ? ? ? ? m_post = post;

? ? ? ? }

? ? ? ? public String format(String hex) {

? ? ? ? ? ? StringReader reader = new StringReader(hex);

? ? ? ? ? ? StringBuilder builder = new StringBuilder(hex.length() * 2);

? ? ? ? ? ? try {

? ? ? ? ? ? ? ? while (getHexLine(builder, reader)) {

? ? ? ? ? ? ? ? }

? ? ? ? ? ? } catch (IOException e) {

? ? ? ? ? ? ? ? // 不應(yīng)該有異常出現(xiàn)。

? ? ? ? ? ? }

? ? ? ? ? ? return builder.toString();

? ? ? ? }

? ? ? ? private boolean getHexLine(StringBuilder builder, StringReader reader)

? ? ? ? ? ? ? ? throws IOException {

? ? ? ? ? ? StringBuilder lineBuilder = new StringBuilder();

? ? ? ? ? ? boolean result = true;

? ? ? ? ? ? for (int i = 0; i < m_row; i++) {

? ? ? ? ? ? ? ? result = getHexByte(lineBuilder, reader);

? ? ? ? ? ? ? ? if (result == false)

? ? ? ? ? ? ? ? ? ? break;

? ? ? ? ? ? }

? ? ? ? ? ? if (lineBuilder.length() > 0) {

? ? ? ? ? ? ? ? builder.append(m_pre);

? ? ? ? ? ? ? ? builder.append(lineBuilder);

? ? ? ? ? ? ? ? builder.append(m_post);

? ? ? ? ? ? }

? ? ? ? ? ? return result;

? ? ? ? }

? ? ? ? private boolean getHexByte(StringBuilder builder, StringReader reader)

? ? ? ? ? ? ? ? throws IOException {

? ? ? ? ? ? char[] hexByte = new char[4];

? ? ? ? ? ? int bytesRead = reader.read(hexByte);

? ? ? ? ? ? if (bytesRead == -1)

? ? ? ? ? ? ? ? return false;

? ? ? ? ? ? builder.append(hexByte, 0, bytesRead);

? ? ? ? ? ? builder.append(" ");

? ? ? ? ? ? return bytesRead == 4;

? ? ? ? }

? ? }

? ? private static final char m_hexCodes[] = {'0', '1', '2', '3', '4', '5',

? ? ? ? ? ? '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

? ? private static final int m_shifts[] = {60, 56, 52, 48, 44, 40, 36, 32, 28,

? ? ? ? ? ? 24, 20, 16, 12, 8, 4, 0};

? ? public static String tablify(byte[] bytes) {

? ? ? ? return (new HexDump()).new HexTablifier().format(HexDump.toHex(bytes));

? ? }

? ? public static String tablify(byte[] bytes, int row) {

? ? ? ? return (new HexDump()).new HexTablifier(row).format(HexDump

? ? ? ? ? ? ? ? .toHex(bytes));

? ? }

? ? public static String tablify(byte[] bytes, int row, String pre) {

? ? ? ? return (new HexDump()).new HexTablifier(row, pre).format(HexDump

? ? ? ? ? ? ? ? .toHex(bytes));

? ? }

? ? public static String tablify(String hex, int row, String pre, String post) {

? ? ? ? return (new HexDump()).new HexTablifier(row, pre, post).format(hex);

? ? }

? ? private static String toHex(final long value, final int digitNum) {

? ? ? ? StringBuilder result = new StringBuilder(digitNum);

? ? ? ? for (int j = 0; j < digitNum; j++) {

? ? ? ? ? ? int index = (int) ((value >> m_shifts[j + (16 - digitNum)]) & 15);

? ? ? ? ? ? result.append(m_hexCodes[index]);

? ? ? ? }

? ? ? ? return result.toString();

? ? }

? ? public static String toHex(final byte value) {

? ? ? ? return toHex(value, 2);

? ? }

? ? public static String toHex(final short value) {

? ? ? ? return toHex(value, 4);

? ? }

? ? public static String toHex(final int value) {

? ? ? ? return toHex(value, 8);

? ? }

? ? public static String toHex(final long value) {

? ? ? ? return toHex(value, 16);

? ? }

? ? public static String toHex(final byte[] value) {

? ? ? ? return toHex(value, 0, value.length);

? ? }

? ? public static String toHex(final byte[] value, final int offset,

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? final int length) {

? ? ? ? StringBuilder retVal = new StringBuilder();

? ? ? ? int end = offset + length;

? ? ? ? for (int x = offset; x < end; x++)

? ? ? ? ? ? retVal.append(toHex(value[x]));

? ? ? ? return retVal.toString();

? ? }

? ? public static byte[] restoreBytes(String hex) {

? ? ? ? byte[] bytes = new byte[hex.length() / 2];

? ? ? ? for (int i = 0; i < bytes.length; ++i) {

? ? ? ? ? ? int c1 = charToNumber(hex.charAt(2 * i));

? ? ? ? ? ? int c2 = charToNumber(hex.charAt(2 * i + 1));

? ? ? ? ? ? if (c1 == -1 || c2 == -1) {

? ? ? ? ? ? ? ? return null;

? ? ? ? ? ? }

? ? ? ? ? ? bytes[i] = (byte) ((c1 << 4) + c2);

? ? ? ? }

? ? ? ? return bytes;

? ? }

? ? private static int charToNumber(char c) {

? ? ? ? if (c >= '0' && c <= '9') {

? ? ? ? ? ? return c - '0';

? ? ? ? } else if (c >= 'a' && c <= 'f') {

? ? ? ? ? ? return c - 'a' + 0xa;

? ? ? ? } else if (c >= 'A' && c <= 'F') {

? ? ? ? ? ? return c - 'A' + 0xA;

? ? ? ? } else {

? ? ? ? ? ? return -1;

? ? ? ? }

? ? }

}

```

<hr style=" border:solid; width:100px; height:1px;" color=#000000 size=1">

# 總結(jié)

<font color=#999AAA >本文章只是提供一個思路携冤,需要改進(jìn)和完善的自己去研究研究悼粮。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市噪叙,隨后出現(xiàn)的幾起案子矮锈,更是在濱河造成了極大的恐慌,老刑警劉巖睁蕾,帶你破解...
    沈念sama閱讀 216,919評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件苞笨,死亡現(xiàn)場離奇詭異,居然都是意外死亡子眶,警方通過查閱死者的電腦和手機(jī)瀑凝,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,567評論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來臭杰,“玉大人粤咪,你說我怎么就攤上這事】矢耍” “怎么了寥枝?”我有些...
    開封第一講書人閱讀 163,316評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長磁奖。 經(jīng)常有香客問我囊拜,道長,這世上最難降的妖魔是什么比搭? 我笑而不...
    開封第一講書人閱讀 58,294評論 1 292
  • 正文 為了忘掉前任冠跷,我火速辦了婚禮,結(jié)果婚禮上身诺,老公的妹妹穿的比我還像新娘蜜托。我一直安慰自己,他們只是感情好霉赡,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,318評論 6 390
  • 文/花漫 我一把揭開白布橄务。 她就那樣靜靜地躺著,像睡著了一般同廉。 火紅的嫁衣襯著肌膚如雪仪糖。 梳的紋絲不亂的頭發(fā)上柑司,一...
    開封第一講書人閱讀 51,245評論 1 299
  • 那天,我揣著相機(jī)與錄音锅劝,去河邊找鬼攒驰。 笑死,一個胖子當(dāng)著我的面吹牛故爵,可吹牛的內(nèi)容都是我干的玻粪。 我是一名探鬼主播,決...
    沈念sama閱讀 40,120評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼诬垂,長吁一口氣:“原來是場噩夢啊……” “哼劲室!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起结窘,我...
    開封第一講書人閱讀 38,964評論 0 275
  • 序言:老撾萬榮一對情侶失蹤很洋,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后隧枫,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體喉磁,經(jīng)...
    沈念sama閱讀 45,376評論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,592評論 2 333
  • 正文 我和宋清朗相戀三年官脓,在試婚紗的時候發(fā)現(xiàn)自己被綠了协怒。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,764評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡卑笨,死狀恐怖孕暇,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情赤兴,我是刑警寧澤妖滔,帶...
    沈念sama閱讀 35,460評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站桶良,受9級特大地震影響铛楣,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜艺普,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,070評論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望鉴竭。 院中可真熱鬧歧譬,春花似錦、人聲如沸搏存。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,697評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽璧眠。三九已至缩焦,卻和暖如春读虏,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背袁滥。 一陣腳步聲響...
    開封第一講書人閱讀 32,846評論 1 269
  • 我被黑心中介騙來泰國打工盖桥, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人潮改。 一個月前我還...
    沈念sama閱讀 47,819評論 2 370
  • 正文 我出身青樓稍坯,卻偏偏與公主長得像线脚,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子塑荒,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,665評論 2 354

推薦閱讀更多精彩內(nèi)容