SD卡读写 android
package com.jredu.helloworld.activity; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.jredu.helloworld.R; import com.jredu.helloworld.entity.SDcard; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class SDActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sd); //XML文件没有给出,就是两个按钮 Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { writetoSD(); } }); Button button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { readtoSD(); } }); } private void writetoSD() { ObjectOutputStream oos = null; String state = Environment.getExternalStorageState();//获取SD卡状态 if (state.equals(Environment.MEDIA_MOUNTED)) { //外部存储正常 File root = Environment.getExternalStorageDirectory();//获取SD根路径 File targetdir = new File(root, super.getPackageName());//在根路径下创建子路径 if (!targetdir.exists()) { targetdir.mkdir(); } try { oos = new ObjectOutputStream(new FileOutputStream(new File(targetdir,"www.txt"))); SDcard sDcard = new SDcard("hello word", "by me"); oos.writeObject(sDcard); Toast.makeText(SDActivity.this, "读入成功", Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); }finally { try { oos.flush(); oos.close(); } catch (IOException e) { e.printStackTrace(); } } } } private void readtoSD() { //读和写大致一样 ObjectInputStream ois=null; String state = Environment.getExternalStorageState(); if (state.equals(Environment.MEDIA_MOUNTED)) { File root = Environment.getExternalStorageDirectory(); File targetdir = new File(root, super.getPackageName()); if (targetdir.exists()) { try { ois = new ObjectInputStream(new FileInputStream(new File(targetdir,"www.txt"))); SDcard sDcard = (SDcard) ois.readObject(); Toast.makeText(SDActivity.this,sDcard.getTitle()+sDcard.getContent(), Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }finally { try { ois.close(); } catch (IOException e) { e.printStackTrace(); } } } } } }
注意:
new File(targetdir,"www.txt")读和写,或+ 要用就要一致。
还有要关闭输入输出流