彻底解决android读取中文txt,lrc的乱码(自动判断文档类型并转码)

这几天在研究android的播放器,在读取歌词的时候,老是乱码,使我很纠结:

今天在网上看到一个文件转码的文章,彻底解决了我的乱码问题,这样我就不用自己去手动的转码lrc歌词文件你的编码了,现在与大家分享一下这一文章(其中里面的几个if  else里面的条件原理不是很懂,请高手帮忙解答):

 

package com.qgmobile.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 转换文件的编码格式
 * @author yangchuxi
 *
 */
public class ConvertFileCode {
 public String converfile(String filepath){
  System.out.println("ConvertFileCode--------->"+filepath);
  File file=new File(filepath);
  FileInputStream fis=null;
  BufferedInputStream bis=null;
  BufferedReader reader=null;
  String text="";
  try {
   fis=new FileInputStream(file);
   bis=new BufferedInputStream(fis);
   bis.mark(4);
   byte[] first3bytes=new byte[3];
//   System.out.println("");
   //找到文档的前三个字节并自动判断文档类型。
   bis.read(first3bytes);
   bis.reset();
     if (first3bytes[0] == (byte) 0xEF && first3bytes[1] == (byte) 0xBB
                      && first3bytes[2] == (byte) 0xBF) {// utf-8

              reader = new BufferedReader(new InputStreamReader(bis, "utf-8"));

      } else if (first3bytes[0] == (byte) 0xFF
                      && first3bytes[1] == (byte) 0xFE) {

              reader = new BufferedReader(
                              new InputStreamReader(bis, "unicode"));
      } else if (first3bytes[0] == (byte) 0xFE
                      && first3bytes[1] == (byte) 0xFF) {

              reader = new BufferedReader(new InputStreamReader(bis,
                              "utf-16be"));
      } else if (first3bytes[0] == (byte) 0xFF
                      && first3bytes[1] == (byte) 0xFF) {

              reader = new BufferedReader(new InputStreamReader(bis,
                              "utf-16le"));
      } else {

              reader = new BufferedReader(new InputStreamReader(bis, "GBK"));
      }
      String str = reader.readLine();

         while (str != null) {
             text = text + str + "/n";
             str = reader.readLine();
           }
         System.out.println("text"+text);
  } catch (Exception e) {
   e.printStackTrace();
  }finally{
   if (fis!=null) {
    try {
     fis.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   if(bis!=null){
    try {
     bis.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  
  return text;
  
 }
}


  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值