日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > Android >内容正文

Android

Android中怎样调用自带的Base64实现文件与字符串的编码和解码

發(fā)布時(shí)間:2025/3/19 Android 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android中怎样调用自带的Base64实现文件与字符串的编码和解码 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

場(chǎng)景

需要將某音頻文件mp3格式編碼成字符串并能再將其轉(zhuǎn)換為字符串。

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
關(guān)注公眾號(hào)
霸道的程序猿
獲取編程相關(guān)電子書、教程推送與免費(fèi)下載。

實(shí)現(xiàn)

首先新建一個(gè)工具類File2StringUtils并在工具類中新建方法實(shí)現(xiàn)將文件編碼為字符串

??? public static String fileToBase64(InputStream inputStream) {String base64 = null;try {byte[] bytes = new byte[inputStream.available()];int length = inputStream.read(bytes);base64 = Base64.encodeToString(bytes, 0, length, Base64.DEFAULT);} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {try {if (inputStream != null) {inputStream.close();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return base64;}

然后在res下新建raw目錄,在此目錄下存放一個(gè)mp3的音頻文件。

?

然后在需要將文件編碼為字符串的地方

InputStream is = getResources().openRawResource(R.raw.b32); msg = File2StringUtils.fileToBase64(is);

然后就可以將此mp3編碼成Base64格式的字符串

?

然后在工具類中再新建一個(gè)解碼的方法 ,通過(guò)

byte[] mp3SoundByteArray = Base64.decode(content, Base64.DEFAULT);// 將字符串轉(zhuǎn)換為byte數(shù)組

剩下的就可以根據(jù)自己的需求將字節(jié)數(shù)據(jù)進(jìn)行相應(yīng)的操作,比如這里是將其存儲(chǔ)到臨時(shí)文件中

并進(jìn)行播放

??? public static void playMp3(String content) {try {byte[] mp3SoundByteArray = Base64.decode(content, Base64.DEFAULT);// 將字符串轉(zhuǎn)換為byte數(shù)組// create temp file that will hold byte arrayFile tempMp3 = File.createTempFile("badao", ".mp3");tempMp3.deleteOnExit();FileOutputStream fos = new FileOutputStream(tempMp3);fos.write(mp3SoundByteArray);fos.close();// Tried reusing instance of media player// but that resulted in system crashes...MediaPlayer mediaPlayer = new MediaPlayer();// Tried passing path directly, but kept getting// "Prepare failed.: status=0x1"// so using file descriptor insteadFileInputStream fis = new FileInputStream(tempMp3);mediaPlayer.setDataSource(fis.getFD());mediaPlayer.prepare();mediaPlayer.start();} catch (IOException ex) {String s = ex.toString();ex.printStackTrace();}}

然后在需要將此字符串編碼解碼為語(yǔ)音文件的地方

File2StringUtils.playMp3(dataContent);

然后就可以將上面編碼的字符串文件解編碼為語(yǔ)音文件并播放。

總結(jié)

以上是生活随笔為你收集整理的Android中怎样调用自带的Base64实现文件与字符串的编码和解码的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。