android读写SD卡中的文件 demo

原创
2014/12/10 21:22
阅读数 1.6K

有时,我们需要将更大的文件保存下来,就不能用手机内置的存储空间,毕竟是有限的,所以将文件保存在SD卡中。

要读写SD卡,首先要知道手机上是否有SD卡,且是否可读写

String str = "";
// 判断是否有SD卡,且可读
str = Environment.getExternalStorageState().equals(
		Environment.MEDIA_MOUNTED) ? "有SD卡,且可读写" : "无SD卡或不可读写";

上述代码即可判断是否有SD卡。

现在有两个按钮:读、写

两个EditText : 读输入, 写输出

-----Main.java

public class Main extends Activity {

	private static final String FILE_NAME = "/myStrongFile.bin";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		final EditText text1 = (EditText) findViewById(R.id.editText1);
		final EditText text2 = (EditText) findViewById(R.id.editText2);
		Button writeButton = (Button) findViewById(R.id.button1);
		Button readButton = (Button) findViewById(R.id.button2);
		String str = "";
		// 判断是否有SD卡,且可读
		str = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED) ? "有SD卡,且可读写" : "无SD卡或不可读写";
		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
		writeButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				write(text1.getText().toString());
				text1.setText("");
			}
		});

		readButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				text2.setText(read());
			}
		});

	}

	private String read() {
		StringBuilder sb = null;
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			// 获取SD卡对应的存储目录   即 /mnt/sdcard/  路径
			File sdCardDir = Environment.getExternalStorageDirectory();
			// 获取指定文件对应的输入流
			FileInputStream fis;
			try {
				fis = new FileInputStream(sdCardDir.getCanonicalPath()
						+ FILE_NAME);
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(fis));
				sb = new StringBuilder("");
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
				reader.close();
				return sb.toString();

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			
		}
		return null;

	
	}

	private void write(String str) {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			try {
				// FileOutputStream(Environment.getExternalStorageDirectory().getCanonicalPath()+FILE_NAME);
				// 获取SD卡的目录
				File sdCardDir = Environment.getExternalStorageDirectory();
				File targetFile = new File(sdCardDir.getCanonicalPath()
						+ FILE_NAME);
				// 向指定的文件中添加内容
				//此处用RandomAccessFile, 用FileOutputStream会把文件清空
				RandomAccessFile raf = new RandomAccessFile(targetFile, "rw");
				// 将文件指针指向最后
				raf.seek(targetFile.length());
				raf.write(str.getBytes());
				raf.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

----main.xml

<RelativeLayout 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"
    tools:context="${relativePackage}.${activityClass}" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="34dp"
        android:layout_marginTop="20dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="42dp"
        android:ems="10"
         />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText2"
        android:layout_below="@+id/editText2"
        android:layout_marginTop="44dp"
        android:text="写入" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:layout_alignRight="@+id/editText1"
        android:layout_marginRight="17dp"
        android:text="读取" />

</RelativeLayout>

布局效果图:

运行发现,写入后,读不出。

原来android读写SD卡需要另外添加权限:

在AndroidManifest.xml中添加权限:

<!-- 在SD卡中创建和删除文件的权限 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <!-- 向SD卡中写入数据的权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

再运行就可以了。这次竟然能显示笑脸了。。。

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部