3.android 读取文件中的数据

package com.wjl.bc;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.http.util.EncodingUtils;

import android.R.string;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class FileManage2Activity extends Activity {
    /** Called when the activity is first created. */
	
	private TextView mytextView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mytextView=(TextView)findViewById(R.id.myTextView);
        
//        this.fileFromRaw();
//        fileFromAsset();
        
//        fileFromSdcard();
        String fileName="Test.txt";
        String message="abcderty";
        writeFileData(fileName, message);
        
        
        
    }
    
    
    //从 resource中的raw 文件夹中获取文件病毒去数据(资源文件只能度不能写)
    public void fileFromRaw()
    {
    	String res="";
    	try {
			InputStream in=getResources().openRawResource(R.raw.abc);
			int length=in.available();
			byte[] buffer=new byte[length];
			in.read(buffer);
			res=EncodingUtils.getString(buffer, "UTF-8");
//			res=EncodingUtils.getString(buffer, "BIG5");
//			res=EncodingUtils.getString(buffer, "UNICODE");
			in.close();
			mytextView.setText(res);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
    }
    
    /**
     * 从asset中获取文件并读出数据(资源文件只能读不能写)
     */
    public void fileFromAsset()
    {
    	String fileName="abc.txt";
    	String res="";
    	try {
			InputStream in=getResources().getAssets().open(fileName);
			int length=in.available();
			byte[] buffer=new byte[length];
			in.read(buffer);
			res=EncodingUtils.getString(buffer, "UTF-8");
			in.close();
			mytextView.setText(res);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
    }
    
    /**
     * 从sdcard 中去读文件,首先要把文件通过 adb.exe push d:\abc.txt\sdcard
     * 
     */
    
    public void fileFromSdcard()
    {
    	String fileName="/sdcard/abc.txt";
    	String res="";
    	try {
			FileInputStream fin=new FileInputStream(fileName);
			int length=fin.available();
			byte[] buffer=new byte[length];
			fin.read(buffer);
			res=EncodingUtils.getString(buffer, "UTF-8");
			fin.close();
			mytextView.setText(res);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
    }
    
    public void writeFileData(String fileName, String message)
    {
    	try {
			FileOutputStream fout=openFileOutput(fileName, MODE_PRIVATE);
			byte[] bytes=message.getBytes();
			fout.write(bytes);
			fout.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
    }
}

你可能感兴趣的:(3.android 读取文件中的数据)