首页 > 代码库 > 文件操作(三)

文件操作(三)

SD卡文件读取操作

EditText et;
	Button   bt1;
	Button   bt2;
	TextView tv;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sdimpl);
		et=(EditText) findViewById(R.id.etkk);
		bt1=(Button) findViewById(R.id.save);
		bt2=(Button) findViewById(R.id.load);
		tv=(TextView) findViewById(R.id.tvkk);
		bt1.setOnClickListener(this);
		bt2.setOnClickListener(this);
	}
	@Override
	public void onClick(View v) {
		//SD判断SD卡是否存在
		if(!Environment.getExternalStorageState()
			 .equals(Environment.MEDIA_MOUNTED)){
			Toast.makeText(this, "SD卡不存在", 3000).show();
			return;
		}
		//创建文件夹对象
		File dir=new File(Environment.getExternalStorageDirectory(),"test");
	    switch(v.getId()){
	    case R.id.save:
	         if(!dir.exists()){
	        	 //如果目录不存在,就创建
	        	 dir.mkdir();
	         }
	         File file=new File(Environment.getExternalStorageDirectory(), "test.txt");
	         try {
				PrintWriter pw=new PrintWriter(file);
				pw.println(et.getText().toString());
				pw.close();
				Toast.makeText(this, "保存成功", 3000).show();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
	    case R.id.load:
	    	file=new File(Environment.getExternalStorageDirectory(),"test.txt");
	    	try {
				BufferedReader br=new BufferedReader(
				new InputStreamReader(
				new FileInputStream(file)));
				String str=null;
				while((str=br.readLine())!=null){
					tv.append(str);
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	break;
	    }
	}

  

 

文件操作(三)