android讀取SDCard任意路徑下的文件

文件不能太大不然會報內存溢出
import java.io.FileInputStream;
import org.apache.http.util.EncodingUtils;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ReadAnythingPathActivity extends Activity {
    TextView textView;

    // 這個是讀取SDCard任意路徑下的文件
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView = (TextView) findViewById(R.id.tvtext);
        String txt = "";
        try {
            // 文件路徑
            String filename = "/sdcard/ansi1.txt";            
            // 或 String filename = "mnt/sdcard/ansi1.txt";
            // 文件流讀取文件
            FileInputStream fin = new FileInputStream(filename);
            // 得到字符長度
            int length = fin.available();
            // 建立字節數組
            byte[] buffer = new byte[length];
            // 把字節流讀入數組中
            fin.read(buffer);
            // 關閉文件流
            fin.close();
            // 得到編碼格式
            String type = codetype(buffer);
            // 使用編碼格式得到內容
            txt = EncodingUtils.getString(buffer, type);
            textView.setText(txt);
        }
        catch(Exception e) {
            // TODO: handle exception
        }
    }

    private String codetype(byte[] head) {
        String type = "";
        byte[] codehead = new byte[3];
        System.arraycopy(head, 0, codehead, 0, 3);
        if(codehead[0] == -1 && codehead[1] == -2) {
            type = "UTF-16";
        }
        else if(codehead[0] == -2 && codehead[1] == -1) {
            type = "UNICODE";
        }
        else if(codehead[0] == -17 && codehead[1] == -69 && codehead[2] == -65) {
            type = "UTF-8";
        }
        else {
            type = "GB2312";
        }
        return type;
    }
}

版權聲明:本文爲博主原創文章,未經博主容許不得轉載。java

相關文章
相關標籤/搜索