在我的应用程序中读取txt文件时出错

时间:2012-11-19 07:40:33

标签: android

感谢您的时间,当我的应用程序在第mycode = "UTF-8"行运行时,它直接跳转到catch.It非常奇怪,因为我只将值设置为mycode字符串。当我读取由以下代码编写的txt文件时ANSI,head[0]head[1]head[2]的值不是-17``-69-65,因此条件应该不满意。但事实是app仍然执行句子mycode = "UTF-8"。我无法弄清楚原因,任何帮助都会被欣赏。

我的代码如下:

package com.example.tyghgy;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import android.util.Log;

public class MyTxt {

    private BufferedReader br = null;
    InputStream in = null;

    public MyTxt(){
          File f=null;
          f= new File("/sdcard/s.txt");
          String sssss;

          try {
           in = new BufferedInputStream(new FileInputStream(f));
           sssss = get_code();
          } catch (FileNotFoundException e3) {
           // TODO Auto-generated catch block
           e3.printStackTrace();
          }

          try {
           br = new BufferedReader(new InputStreamReader(in, "utf-8"));
          } catch (UnsupportedEncodingException e1) {
           // TODO Auto-generated catch block
           e1.printStackTrace();
          }


    }


    private String get_code(){
        String mycode = "";  
        byte[] head = new byte[3];  
        try{
        in.read(head);  

        if (head[0] == -1 && head[1] == -2 )  
            mycode = "UTF-16";  
        if (head[0] == -2 && head[1] == -1 )  
            mycode = "Unicode";  
        if(head[0]==-17 && head[1]==-69 && head[2] ==-65)  
            mycode = "UTF-8";  

        return mycode;
        }catch (Exception e) {
            // TODO: handle exception
            Log.v("sssssssssss", e.getMessage());
            mycode = e.getMessage();
            return mycode;
        }
    }
}

1 个答案:

答案 0 :(得分:3)

使用Environment.getExternalStorageDirectory().getAbsolutePath()获取SDCARD的路径:

String sdcardpath = Environment.getExternalStorageDirectory().getAbsolutePath();
String fName = "s.txt";
File f = new File(sdcardpath + File.separator + fName);
//Your Code...

并确保您在清单中添加了以下权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>