读写SD卡上的文件有几个步骤
1.调用Environment的getExternalStorageState() 方法判断手机上是否插入了SD卡,并且应用程序具有读写权限
如使用如下代码
//如果手机已插入SD卡,且应用程序具有读写SD卡的能力,下面语句返回true
Environment.getExternalstorageState().equals(Environment.MEDIA_MOUNTED)
2.调用Environment的getExternalStorageDirectory()方法来获取外部存储器,也就是SD卡的目录
3.使用FileInputStream,FileOutputStream,FileReader或FileWriter读,写SD卡里的文件
此外必须向AndroidManifest.xml添加SD卡的读写权限
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
下面是一个示例,用来读写SD卡里的文件
package WangLi.IO.SDCardTest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
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 SDCardTest extends Activity {
final String FILE_NAME = "/sdcardtest.txt";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//获取两个按钮
Button read = (Button)findViewById(R.id.read);
Button write = (Button)findViewById(R.id.write);
//获取两个文本框
final EditText edit1 = (EditText)findViewById(R.id.edit1);
final EditText edit2 = (EditText)findViewById(R.id.edit2);
//为write按钮绑定事件监听器
write.setOnClickListener(new OnClickListener(){
public void onClick(View source)
{
write(edit1.getText().toString());
edit1.setText("");
}
});
//为read按钮绑定事件监听器
read.setOnClickListener(new OnClickListener(){
public void onClick(View source)
{
//读取指定文件中的内容并显示出来
edit2.setText(read());
}
});
}
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);
}
return sb.toString();
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
private void write(String content)
{
try
{
//如果手机插入了SD卡,而且应用程序具有访问SD的权限
if(Environment.getExternalStorageState()
.equals(Environment.MEDIA_MOUNTED))
{
//获取SD卡根目录
File sdCardDir = Environment.getExternalStorageDirectory();
File targetFile = new File(sdCardDir.getCanonicalPath() + FILE_NAME);
//以指定文件创建RandomAccessFile对象
RandomAccessFile raf = new RandomAccessFile(targetFile, "rw");
//将文件记录指针移动到最后
raf.seek(targetFile.length());
//输出文件内容
raf.write(content.getBytes());
raf.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
上面有两个按钮,两个文本框,和上一篇一样,一个用来读,一个用来写
写入后,可以在DMSS里面找到刚刚写入的文件