android学习笔记9--------------SD卡读写文件
上一篇:http://www.zzzyk.com/kf/201202/119873.html
把文件存入SD卡中
首先加入读写权限
SD卡创建与删除文件权限
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>
SD卡写入数据权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
点击保存前:
点击保存:
SD卡根目录多了123.txt文件
点击读取:
读取成功。
代码:
[java]
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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;
import android.widget.TextView;
import android.widget.Toast;
import com.luku.file.service.FileService;
public class fileActivity extends Activity
{
private EditText editText=null;
private Button button =null;
private TextView content =null;
private Button read=null;
private TextView textView1=null;
private Button exit=null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView1=(TextView)findViewById(R.id.textView1);
content=(TextView)findViewById(R.id.content);
editText=(EditText)findViewById(R.id.filename);
button=(Button)findViewById(R.id.baocun);
read=(Button)findViewById(R.id.read);
exit=(Button)findViewById(R.id.exit);
button.setOnClickListener(listener);
read.setOnClickListener(listener);
exit.setOnClickListener(listener);
}
private OnClickListener listener=new OnClickListener()
{
int resId = R.string.success;
@Override
public void onClick(View v)
{
Button btn=(Button)v;
File file=new File(Environment.getExternalStorageDirectory(),//得到SD卡根目录
editText.getText().toString()); //保存文件的文件名
switch (btn.getId())
{
case R.id.baocun:
if(Environment.getExternalStorageState().
equals(Environment.MEDIA_MOUNTED)) //判断SD卡是否存在,并且可以可以读写
{
try
{
FileOutputStream stream=new FileOutputStream(file);
FileService.save(stream, content.getText().toString());
}
catch (IOException e)
{
e.printStackTrace();
resId = R.string.error;
Toast.makeText(fileActivity.this, resId, Toast.LENGTH_LONG).show();
}
Toast.makeText(fileActivity.this, resId, Toast.LENGTH_LONG).show();
}
else
&nbs
补充:移动开发 , Android ,