课堂整理:写入和读取外部存储文件
layout代码:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context="com.example.my.testapp.MainActivity"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Hello World!" android:id="@+id/tv_1"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="sp存储" android:onClick="bt_onClick"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="sp读取" android:onClick="bt1_onClick"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="输入。。。" android:id="@+id/et_1"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="bt2_onClick" android:text="写入内部文件"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="bt3_onClick" android:text="读内部文件"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="bt4_onClick" android:text="保存资产文件到内部空间"/> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/iv_1" android:src="@drawable/sword"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="bt5_onClick" android:text="设置图片指向内部存储"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="bt6_onClick" android:text="写入外部存储文件"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="bt7_onClick" android:text="读取外部存储文件"/> </LinearLayout>
Activity代码:
package com.example.my.testapp; import android.content.SharedPreferences; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.PrintStream; public class MainActivity extends AppCompatActivity { EditText et_1; TextView tv_1; ImageView iv_1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_1=(EditText)findViewById(R.id.et_1); tv_1=(TextView)findViewById(R.id.tv_1); iv_1=(ImageView)findViewById(R.id.iv_1); } public void bt_onClick(View v) { //1.得到SharedPreferences对象 SharedPreferences sharedPreferences=getSharedPreferences("abc",MODE_APPEND); //2.得到编辑器 SharedPreferences.Editor editor=sharedPreferences.edit(); //3.使用Editor添加数据 // editor.putString("a","abcdef"); // editor.putString("b","xxxxxx"); // editor.putLong("long",123456); editor.remove("a"); //4.提交保存 editor.commit(); Toast.makeText(MainActivity.this, "保存数据成功。", Toast.LENGTH_SHORT).show(); } //读取 public void bt1_onClick(View v) { SharedPreferences sp=getSharedPreferences("abc",MODE_PRIVATE); String str=sp.getString("b", null); Toast.makeText(MainActivity.this, "key=b"+"value="+str, Toast.LENGTH_SHORT).show(); } //写内部文件 public void bt2_onClick(View v) { //从内存里写入文件 //1.得到内部的存储目录 try { File file = getFilesDir(); String path = file.getAbsolutePath(); Toast.makeText(MainActivity.this, "path=" + path, Toast.LENGTH_SHORT).show(); //2.用输出流写入文件 FileOutputStream fos = openFileOutput("test.txt", MODE_APPEND); //3.写入内容 PrintStream ps=new PrintStream(fos); String str=et_1.getText().toString(); ps.println(str); ps.println("自动换行"); ps.close(); fos.close(); Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_SHORT).show(); } catch (Exception e) { } } public void bt3_onClick(View v) { try { //输入流 FileInputStream fis = openFileInput("test.txt"); //1.定义byte[] byte[] b =new byte[1024]; int i=0;//读到的数据长度 String str1=""; //2.循环读 while ((i=fis.read(b))>0) { String str = new String(b,0,i); str1 += str; } fis.close(); tv_1.setText(str1); } catch (Exception ex) { } } public void bt4_onClick(View v) { try { //操作assets目录的文件 //1.得到assetsManager AssetManager assetManager = getAssets(); //2.操作资产目录,边读边写入 //1) 读文件到内存 inputstream InputStream inputStream = assetManager.open("female.png"); //2) 写文件到目录 outputstream FileOutputStream fos=openFileOutput("test.png",MODE_PRIVATE); //先读后写 byte [] b=new byte[1024]; int i=0; while ((i=inputStream.read(b))>0) { fos.write(b,0,i); } fos.close(); inputStream.close(); Toast.makeText(MainActivity.this, "保存文件成功", Toast.LENGTH_SHORT).show(); } catch (Exception ex) { Toast.makeText(MainActivity.this, "保存文件出错", Toast.LENGTH_SHORT).show(); } } public void bt5_onClick(View v) { //得到文件路径 String path=getFilesDir().getAbsolutePath()+"/test.png"; Toast.makeText(MainActivity.this, "path="+path, Toast.LENGTH_SHORT).show(); // 从内部存储的图片得到 Bitmap,BitmapFactory.decodeFile("文件途径"); Bitmap bm= BitmapFactory.decodeFile(path); //设置图片视图的图片来源 iv_1.setImageBitmap(bm); } public void bt6_onClick(View v) { //1.判断sd卡是否挂载 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { //文本框内容 String str=et_1.getText().toString(); try { //写入 //1.构造输出流 //1) 得到文件路径 //得到SD卡根目录 //String path=Environment.getExternalStorageDirectory().getCanonicalPath(); //得到包名对应的目录 String path=getExternalFilesDir("Music").getCanonicalPath(); Toast.makeText(MainActivity.this, "path="+path, Toast.LENGTH_SHORT).show(); //2)构造 FileOutputStream fos = new FileOutputStream(path + "/test.txt"); PrintStream ps=new PrintStream(fos); ps.print(str); ps.close(); fos.close(); Toast.makeText(MainActivity.this, "写入外部文件成功", Toast.LENGTH_SHORT).show(); } catch (Exception ex) { Toast.makeText(MainActivity.this, "存储文件出错", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(MainActivity.this, "SD卡没有挂载", Toast.LENGTH_SHORT).show(); } } public void bt7_onClick(View v) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { try { String path = getExternalFilesDir("Music").getCanonicalPath() + "/test.txt"; FileInputStream fis= new FileInputStream(path); byte [] b=new byte[1024]; int i=0; String str=""; while ((i=fis.read(b))>0) { str+=new String(b,0,i); } fis.close(); Toast.makeText(MainActivity.this, "文件内容="+str, Toast.LENGTH_SHORT).show(); } catch (Exception ex) { Toast.makeText(MainActivity.this, "读取外部文件失败", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(MainActivity.this, "SD卡没有挂载", Toast.LENGTH_SHORT).show(); } } }