//注意不能直接向外部存储写文件,所以要想外部存储写文件还必须要有权限才可以,因此需要在androidManifest.xml文件中加入写入外部文件的的权限
核心代码段
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//注意不能直接向外部存储写文件,所以要想外部存储写文件还必须要有权限才可以,因此需要在
//androidManifest.xml文件中加入写入外部文件的的权限
//找到外部存储文件目录
File dir = Environment.getExternalStorageDirectory();
//设置文件的保存目录
File dataFile = new File(dir,"data.txt");
try{
//用于读取外部存储卡的文件中的数据
FileInputStream fis = new FileInputStream(dataFile);
byte [] bytes = new byte[fis.available()];
fis.read(bytes);
fis.close();
String text = new String(bytes,"utf-8");
System.out.println(text);
}catch(Exception e)
{
}
//用于将数据保存到外部存储卡上
try {
//如果sd卡没被挂载上,那么就可能引发异常
if(!dataFile.exists())
dataFile.createNewFile();
//创建输出流
FileOutputStream fos = new FileOutputStream(dataFile);
fos.write(new String("hello zhangfucheng ").getBytes("utf-8"));
System.out.println("hello");
fos.flush();
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}