14_把文件存放在SDCard

权限添加

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    /**
* 保存到SD卡
* @param filename
* @param content
* @throws Exception
*/
public void saveToSDCard(String filename, String content) throws Exception{
// TODO Auto-generated method stub
// MODE_PRIVATE:创建出来的文件仅能被本应用访问,另外采用私有模式创建的文件写入文件中的内容会覆盖原文件的内容
File file = new File(Environment.getExternalStorageDirectory(), content);
FileOutputStream outStream = new
FileOutputStream(file);
outStream.write(content.getBytes());
outStream.close();
}
    private final class ButtonClickListener implements View.OnClickListener{

        public void onClick(View v){
String filename = filenameText.getText().toString();
String content = contentText.getText().toString();
FileService service = new FileService(getApplicationContext());
try {
// 方法1:写入手机内存
//service.save(filename, content);
//Toast.makeText(getApplicationContext(),"R.string.success"/*R.string.success*/, Toast.LENGTH_SHORT);
// 方法2:写入SD卡
if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)){
service.saveToSDCard(filename, content);
Toast.makeText(getApplicationContext(),"R.string.success"/*R.string.success*/, Toast.LENGTH_SHORT);
}
else{
Toast.makeText(getApplicationContext(),"sd failed"/*R.string.success*/
, Toast.LENGTH_SHORT);
}
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "failed"/*R.string.fail*/, Toast.LENGTH_SHORT);
e.printStackTrace();
} }
}
上一篇:(5)ASP.NET Core 中的静态文件


下一篇:Vue依赖收集引发的问题