Android读取中文文件乱码解决方法

最近在做个MP3播放器,出现中文乱码问题,在网上找了很多解决办法,我整理了出现乱码的点和解决方案,拿出来和大家共享一下 

1.读取中文文件乱码解决方法 

package com.apj.conv;  

  

import java.io.BufferedInputStream;  

import java.io.BufferedReader;  

import java.io.File;  

import java.io.FileInputStream;  

import java.io.FileNotFoundException;  

import java.io.IOException;  

import java.io.InputStreamReader;  

  

import android.app.Activity;  

import android.os.Bundle;  

import android.os.Environment;  

import android.widget.TextView;  

  

public class ConverActivity extends Activity {  

      

    private TextView textview ;  

      

    @Override  

    public void onCreate(Bundle savedInstanceState) {  

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.main);  

          

        textview = (TextView) findViewById(R.id.lrctext);  

        

        System.out.println("==============convertCodeAndGetText begin============== ");  

        ///获得SDCard中文件的路径  

        String path = Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator ;  

        String tochinese = convertCodeAndGetText(path+"a.txt");  

        System.out.println(tochinese);  

        System.out.println("==============cconvertCodeAndGetText end==============");  

        textview.setText(tochinese);  

    }  

     

    public String convertCodeAndGetText(String str_filepath) {//转变编码 

  

        File file = new File(str_filepath);  

        BufferedReader reader;  

        String text = "";  

        try {  

              

            FileInputStream fis = new FileInputStream(file);  

            BufferedInputStream in = new BufferedInputStream(fis);  

            in.mark(4);  

            byte[] first3bytes = new byte[3];  

            in.read(first3bytes);  

            in.reset();  

            if (first3bytes[0] == (byte) 0xEF && first3bytes[1] == (byte) 0xBB  

                    && first3bytes[2] == (byte) 0xBF) {// utf-8  

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

            } else if (first3bytes[0] == (byte) 0xFF  

                    && first3bytes[1] == (byte) 0xFE) {  

                  reader = new BufferedReader(new InputStreamReader(in, "unicode"));  

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

                  reader = new BufferedReader(new InputStreamReader(in,  "utf-16be"));  

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

                  reader = new BufferedReader(new InputStreamReader(in,  "utf-16le"));  

            } else {  

                  reader = new BufferedReader(new InputStreamReader(in, "GBK"));  

            }  

            String str = reader.readLine();  

  

            while (str != null) {  

                text = text + str + "\n";  

                str = reader.readLine();  

            }  

            reader.close();  

      } catch (FileNotFoundException e) {  

            // TODO Auto-generated catch block  

            e.printStackTrace();  

        } catch (IOException e) {  

            e.printStackTrace();  

        }  

        return text;  

    }  

  

}  

package com.apj.conv;

import java.io.BufferedInputStream;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStreamReader;

import android.app.Activity;

import android.os.Bundle;

import android.os.Environment;

import android.widget.TextView;

public class ConverActivity extends Activity {

private TextView textview ;

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        

        textview = (TextView) findViewById(R.id.lrctext);

        

      

System.out.println("===================convertCodeAndGetText begin=================== ");

    ///获得SDCard中文件的路径

String path = Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator ;

    String tochinese = convertCodeAndGetText(path+"a.txt");

System.out.println(tochinese);

System.out.println("===================cconvertCodeAndGetText end===================");

        textview.setText(tochinese);

        

    }

   

public String convertCodeAndGetText(String str_filepath) {// ת��

File file = new File(str_filepath);

BufferedReader reader;

String text = "";

try {

    

FileInputStream fis = new FileInputStream(file);

BufferedInputStream in = new BufferedInputStream(fis);

in.mark(4);

byte[] first3bytes = new byte[3];

in.read(first3bytes);

in.reset();

if (first3bytes[0] == (byte) 0xEF && first3bytes[1] == (byte) 0xBB

&& first3bytes[2] == (byte) 0xBF) {// utf-8

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

} else if (first3bytes[0] == (byte) 0xFF

&& first3bytes[1] == (byte) 0xFE) {

reader = new BufferedReader(

new InputStreamReader(in, "unicode"));

} else if (first3bytes[0] == (byte) 0xFE

&& first3bytes[1] == (byte) 0xFF) {

reader = new BufferedReader(new InputStreamReader(in,

"utf-16be"));

} else if (first3bytes[0] == (byte) 0xFF

&& first3bytes[1] == (byte) 0xFF) {

reader = new BufferedReader(new InputStreamReader(in,

"utf-16le"));

} else {

reader = new BufferedReader(new InputStreamReader(in, "GBK"));

}

String str = reader.readLine();

while (str != null) {

text = text + str + "\n";

str = reader.readLine();

}

reader.close();

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return text;

}

}

2. 连接网络读取文件内容中文乱码解决办法 

 URL myFileUrl = null;     

   myFileUrl = new URL(url);  

   HttpURLConnection conn;  

   conn = (HttpURLConnection) myFileUrl.openConnection();  

   conn.setDoInput(true);  

   conn.connect();  

   InputStream is = conn.getInputStream();  

   BufferedReader br = new BufferedReader(new InputStreamReader(is,  "GB2312"));  

   sb = new StringBuffer();  

   String data = "";  

   while ((data = br.readLine()) != null) {     

        sb.append(data+"\n");     

   }     

   String result = sb.toString();  

URL myFileUrl = null;   

   myFileUrl = new URL(url);

   HttpURLConnection conn;

   conn = (HttpURLConnection) myFileUrl.openConnection();

   conn.setDoInput(true);

   conn.connect();

   InputStream is = conn.getInputStream();

   BufferedReader br = new BufferedReader(new InputStreamReader(is,

     "GB2312"));

   sb = new StringBuffer();

   String data = "";

   while ((data = br.readLine()) != null) {   

        sb.append(data+"\n");   

   }   

   String result = sb.toString();



3.读取网络文件中文名下载乱码解决办法 
1.先在设置服务器编码:找到Tomcat安装目录下的server.xml文件(Tomcat 6.0\conf\server.xml)。设置编码为UTF-8 

<Connector port="8080" URIEncoding="UTF-8" redirectPort="8443" connectionTimeout="20000" protocol="HTTP/1.1"/> 

2. android 中代码为: 

try {  

          lrcUrl = "http://192.168.0.214/vote/mp3/" + URLEncoder.encode("中文.mp3","UTF-8");  

        } catch (UnsupportedEncodingException e) {  

            // TODO Auto-generated catch block  

            e.printStackTrace();  

        }  

  

        int result1 = downFile(lrcUrl, "mp3/", "中文.mp3");  

**  

 * 该函数返回整型( -1:代表下载文件出错 0:代表下载成功;1:代表文件已存在)  

 **/  

public int downFile(String urlStr, String path, String fileName) {  

    InputStream inputStream = null;  

    try {  

        FileUtils fileUtils = new FileUtils();  

        if (fileUtils.isFileExist( fileName,path )) {  

            return 1;  

        } else {  

            inputStream = getInputStreamFromUrl(urlStr);  

            File resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);  

            if (resultFile == null) {  

                return -1;  

            }  

        }  

    } catch (Exception e) {  

        // TODO: handle exception  

        e.printStackTrace();  

        return -1;  

    } finally {  

        try {  

            inputStream.close();  

        } catch (Exception e2) {  

            e2.printStackTrace();  

        }  

    }  

    return 0;  

}  

  

/** 

 * 根据URL得到输入流 

 *  

 * @param urlStr 

 * @return 

 * @throws MalformedURLException 

 * @throws IOException 

 */  

  

public InputStream getInputStreamFromUrl(String urlStr)  

        throws MalformedURLException, IOException {  

    url = new URL(urlStr);  

    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  

    InputStream inputStream = urlConn.getInputStream();  

    return inputStream;  

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值