8.读取外部存储文件

Environment.getExternalStorageDirectory()获取存储卡的路径
有4种状态:
MEDIA_UNKNOWN:不能识别sd卡
MEDIA_REMOVED:没有sd卡
MEDIA_UNMOUNTED:SD卡存在但是没有挂载
MEDIA_CHECKING:sb卡正在准备
MEDIA_MOUNTED:sd卡已经挂载,可以用


public class MainActivity extends Activity {


    private EditText et_name;
	private EditText et_pass;




	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        et_name = (EditText) findViewById(R.id.et_name);
    	et_pass = (EditText) findViewById(R.id.et_pass);
        read();
    }
    
    //读取文件
    public void read(){
    	//使用api读取路径
    	 //File file = new File("sdcard/12.txt");
    	 File file = new File(Environment.getExternalStorageDirectory(),"123.txt");
    	 if(file.exists()){
	    	 try {
	    		 
				FileInputStream fis = new FileInputStream(file);
				//把字节流转换成字符流
				BufferedReader br = new BufferedReader(new InputStreamReader(fis));
				//读取txt里面的数据,readLine可以读取一行数据
				String text = br.readLine();
				String[] s = text.split("==");
		    	
		    	et_name.setText(s[0]);
		    	et_pass.setText(s[1]);
		    	fis.close();
		    	br.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	 
    	 }
    }


    //点击登陆写文件
    public void login(View v){
    	
    	CheckBox cb = (CheckBox) findViewById(R.id.cb);
    	String name = et_name.getText().toString();
    	String password = et_pass.getText().toString();
    	
    	if(cb.isChecked()){
    		//data/data/com.ldw.rwinrom:存储空间的路径
    		//File file = new File("sdcard/12.txt");
    		File file = new File(Environment.getExternalStorageDirectory(),"123.txt");
    		
    		try {
    			FileOutputStream fos = new FileOutputStream(file);
				fos.write((name + "==" + password).getBytes());
				fos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	
    	Toast.makeText(this, "登陆成功", Toast.LENGTH_SHORT).show();
    	
    }


你可能感兴趣的:(android)