问题描述:

Thanks for your time ,when my app run at line mycode = "UTF-8"and it jump directly to the catch.It's very strange because I only set values to the string mycode.furthermore when I read txt files that are coded by ANSI,values of head[0],head[1] and head[2]are not -17``-69and-65,so the condition supposed to be dissatisfy.but the fact is app still execute the sentencemycode = "UTF-8".I can't figure out the reason ,any help will be appreciate.

my code is below:

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;

}

}

}

网友答案:

Use Environment.getExternalStorageDirectory().getAbsolutePath() for getting path of SDCARD as:

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

And also make sure you have added following permission in manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
相关阅读:
Top