Service方法
...... public class FileService { private static String TAG = "FileManager"; private Context context; ...... /** * 向SDCard中写文件 * @param name * @param content * @throws Exception */ public void saveFileToSDCard(String fileName, String content) throws Exception { //检验手机是否存在SDCard, SDCard是否是写保护的 if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { throw new Exception("SDCard不存在或是写保护的"); } FileOutputStream fos = null; try { fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), fileName)); fos.write(content.getBytes()); } catch (Exception e) { throw new Exception(e); } finally { if(fos != null) { fos.close(); } } } public String readFileFromSDCard(String fileName) throws Exception { //检验手机是否存在SDCard, SDCard是否是写保护的 if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && !Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)) { throw new Exception("SDCard不存在或是不可读"); } FileInputStream fis = null; String content = null; ByteArrayOutputStream os = new ByteArrayOutputStream(); try { fis = new FileInputStream(new File(Environment.getExternalStorageDirectory(), fileName)); byte[] buffer = new byte[1024]; int length = 0; while((length = fis.read(buffer)) >= 0) { os.write(buffer, 0, length); } content = new String(os.toByteArray()); } catch (Exception e) { throw new Exception(e); } finally { if(fis != null) { fis.close(); } if(os != null) { os.close(); } } return content; } public Context getContext() { return context; } public void setContext(Context context) { this.context = context; } }
activity中调用
Button saveToSDCardBtn = (Button) findViewById(R.id.save_to_sdcard_btn_view); saveToSDCardBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String fileName = fileNameView.getText().toString(); String content = fileContentView.getText().toString(); try { fileService.saveFileToSDCard(fileName, content); } catch (Exception e) { Toast.makeText(getApplicationContext(), R.string.save_fail, Toast.LENGTH_SHORT).show(); e.printStackTrace(); } Toast.makeText(getApplicationContext(), R.string.save_successful, Toast.LENGTH_SHORT).show(); } });
因为读写SDCard不是一个安全的行为,所以要在清单文件中配置一些权限
<!-- 往SDCard创建和删除文件的权限 --> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <!-- 往SDCard中写东西的权限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
然后就可以进行测试了。
浙公网安备 33010602011771号