Android中怎样调用自带的Base64实现文件与字符串的编码和解码
生活随笔
收集整理的這篇文章主要介紹了
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)題。
- 上一篇: AndroidStudio中将项目运行在
- 下一篇: Android中怎样使用MediaPla