首页 > 学院 > 开发设计 > 正文

读写SD卡上的文件

2019-11-09 16:21:24
字体:
来源:转载
供稿:网友

布局界面为【输入框】、【显示框】、【数据写入按钮】和【数据输出按钮】

为了读写SD卡上的数据,必须在应用程序的清单文件中添加读写SD卡的权限

在SD卡中创建与删除文件权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>向SD卡写入数据的权限:

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

程序代码如下:

package com.twac.sdcardtest;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.RandomaccessFile;import android.app.Activity;import android.os.Bundle;import android.os.Environment;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;public class MainActivity extends Activity {	PRivate Button btn_write;	private Button btn_read;	private EditText edt_write;	private EditText edt_read;	private final String FILE_NAME = "/crazyit.bin";	@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.activity_main);		btn_write = (Button) findViewById(R.id.btn_write);		btn_read = (Button) findViewById(R.id.btn_read);		edt_write = (EditText) findViewById(R.id.edt_write);		edt_read = (EditText) findViewById(R.id.edt_read);		btn_write.setOnClickListener(new OnClickListener() {			@Override			public void onClick(View arg0) {				// 将edt_write的内容写入文件中				write(edt_write.getText().toString());				edt_write.setText("");			}		});		btn_read.setOnClickListener(new OnClickListener() {			@Override			public void onClick(View arg0) {				edt_read.setText(read());			}		});	}	private void write(String content) {		if (Environment.getExternalStorageState().equals(				Environment.MEDIA_MOUNTED)) {			// 获得SD卡的目录			File sdCardDir = Environment.getExternalStorageDirectory();			try {				File targetFile = new File(sdCardDir.getCanonicalPath()						+ FILE_NAME);				// 以指定文件创建RandomAccessFile对象				RandomAccessFile raf = new RandomAccessFile(targetFile, "rw");				// 将文件记录指针移动到最后				raf.seek(targetFile.length());				// 输出文件内容				raf.write(content.getBytes());				// 关闭RandomAccessFile				raf.close();			} catch (IOException e) {				e.printStackTrace();			}		}	}	private String read() {		try {			// 如果手机插入了SD卡,而且应用程序具有访问SD的权限			if (Environment.getExternalStorageState().equals(					Environment.MEDIA_MOUNTED)) {				// 获取SD卡对应的存储目录				File sdCardDir = Environment.getExternalStorageDirectory();				// 获取指定文件对应的输入流				FileInputStream fis = new FileInputStream(						sdCardDir.getCanonicalPath() + FILE_NAME);				// 将指定输入流包装成BufferedReader				BufferedReader br = new BufferedReader(new InputStreamReader(						fis));				StringBuilder sb = new StringBuilder("");				String line = null;				// 循环读取文件内容				while ((line = br.readLine()) != null) {					sb.append(line);				}				// 关闭资源				br.close();				return sb.toString();			}		} catch (Exception e) {			e.printStackTrace();		}		return null;	}}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表