【Android(安卓)开发教程】保存到外部存储设备(SD卡)
16lz
2021-01-26
本章节翻译自《Beginning-Android-4-Application-Development》,如有翻译不当的地方,敬请指出。
原书购买地址http://www.amazon.com/Beginning-Android-4-Application-Development/dp/1118199545/上一节介绍了如何把文件存储到内部设备。有的时候,需要把文件存储到外部存储设备,比如SD卡。因为SD卡具有更大的存储空间,同时也可以很容易的和其他用户分享这些文件。
使用上一节的例子,把用户输入的文字保存在SD卡,修改onClick()事件。如下:
public class FilesActivity extends Activity {EditText textBox;static final int READ_BLOCK_SIZE = 100;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);textBox = (EditText) findViewById(R.id.txtText1); InputStream is = this.getResources().openRawResource(R.raw.textfile); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String str = null; try { while ((str = br.readLine()) != null) { Toast.makeText(getBaseContext(), str, Toast.LENGTH_SHORT).show(); } is.close(); br.close(); } catch (IOException e) { e.printStackTrace(); }}public void onClickSave(View view) {String str = textBox.getText().toString();try{ //---SD Card Storage--- File sdCard = Environment.getExternalStorageDirectory(); File directory = new File (sdCard.getAbsolutePath() + "/MyFiles"); directory.mkdirs(); File file = new File(directory, "textfile.txt"); FileOutputStream fOut = new FileOutputStream(file); /*FileOutputStream fOut =openFileOutput("textfile.txt",MODE_WORLD_READABLE);*/ OutputStreamWriter osw = newOutputStreamWriter(fOut);//---write the string to the file---osw.write(str);osw.flush(); osw.close();//---display file saved message---Toast.makeText(getBaseContext(),"File saved successfully!",Toast.LENGTH_SHORT).show();//---clears the EditText---textBox.setText("");}catch (IOException ioe){ioe.printStackTrace();}}}上面的代码中,使用getExternalStorageDirectory()方法去获取SD卡的路径。通常,在真机上面返回“/sdcard”,在模拟器上面返回"/mnt/sdcard"。但是,不要尝试去写死SD卡的路径,因为手机厂商有可能去给SD卡指定一个路径。因此,确保使用getExternalStorageDirectory()方法去获取SD卡的路径。
然后,创建一个MyFiles的文件夹。最终,把文件保存在这个文件夹中。
从外部设备中加载文件,修改onClickLoad()方法:
public void onClickLoad(View view) {try{//---SD Storage--- File sdCard = Environment.getExternalStorageDirectory(); File directory = new File (sdCard.getAbsolutePath() + "/MyFiles"); File file = new File(directory, "textfile.txt"); FileInputStream fIn = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fIn); /*FileInputStream fIn = openFileInput("textfile.txt");InputStreamReader isr = new InputStreamReader(fIn); */ char[] inputBuffer = new char[READ_BLOCK_SIZE];String s = "";int charRead;while ((charRead = isr.read(inputBuffer))>0){//---convert the chars to a String---String readString =String.copyValueOf(inputBuffer, 0,charRead);s += readString;inputBuffer = new char[READ_BLOCK_SIZE];}//---set the EditText to the text that has been // read---textBox.setText(s);Toast.makeText(getBaseContext(),"File loaded successfully!",Toast.LENGTH_SHORT).show();}catch (IOException ioe) {ioe.printStackTrace();}}
请注意,如果想要往SD卡中写入文件,需要在AndroidManifest.xml中加入相关的权限:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.manoel.Files" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:label="@string/app_name" android:name=".FilesActivity" > <intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest>
执行上述代码,查看SD卡:
更多相关文章
- (Android、Java) AES加密方法
- Android(安卓)Studio用法之ListView(图文并茂的listview界面)
- android 4.4 沉浸式状态栏实现
- Android引用第三方jar的问题
- AIDL接口描述语言的使用
- [Android]获取设备IP地址
- Android(安卓)Studio 3.0+添加ButterKnife依赖报错的解决办法
- 解决Android9.0网络请求无效问题
- Android(安卓)打开网络上pdf文件