读取SD卡
- 权限配置:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText etText;
private TextView tvShow;
private File sdCardPath = Environment.getExternalStorageDirectory();
private String fileName = "Myfile";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etText = (EditText) findViewById(R.id.etText);
tvShow = (TextView) findViewById(R.id.tvShow);
findViewById(R.id.btnWrite).setOnClickListener(this);
findViewById(R.id.btnRead).setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnWrite:
File file = new File(sdCardPath,fileName);
if (!sdCardPath.exists()){
Toast.makeText(getApplicationContext(),"当前系统没有SD卡目录",Toast.LENGTH_SHORT).show();
return;
}
if (!file.exists()){
try {
file.createNewFile();
Toast.makeText(getApplicationContext(),"文件创建成功",Toast.LENGTH_SHORT).show();
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
osw.write(etText.getText().toString());
Toast.makeText(getApplicationContext(),"文件写入完成",Toast.LENGTH_SHORT).show();
etText.setText("");
osw.flush();
fos.flush();
osw.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
break;
case R.id.btnRead:
if (!sdCardPath.exists()){
Toast.makeText(getApplicationContext(),"当前系统没有SD卡目录",Toast.LENGTH_SHORT).show();
return;
}
File fileRead = new File(sdCardPath,fileName);
if (fileRead.exists()){
try {
FileInputStream fis = new FileInputStream(fileRead);
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
char[] buffer = new char[fis.available()];
isr.read(buffer);
String strBuf = new String(buffer);
tvShow.setText(strBuf);
isr.close();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
}