Android读写SD卡上的数据

在genymotion模拟器中,sd卡文件数据的位置是/mnt/emulated/0

package com.example.myfileupdate;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

/**
 * 文件操作类,用来进行文件操作
 * */

public class FileUtil {

    private Context context;

    public FileUtil(Context context) {

        this.context = context;
    }

    /**
     * 往文件写入数据
     * 
     * @param data
     *            数据
     * @param fileName
     *            文件名称
     * @param mode
     *            文件的创建模式
     * @throws FileNotFoundException
     */

    public void writeData(String data, String fileName, int mode)
            throws Exception {
        // 创建写入文件输入流对象
        FileOutputStream fos = context.openFileOutput(fileName, mode);
        // 写入数据内容
        saveFile(data, fos);
    }

    /**
     * 往文件读取数据
     * 
     * @param fileName
     *            文件名
     * @return
     * @throws IOException
     */
    public String readData(String fileName) throws IOException {

        // 创建文件输入流对象
        FileInputStream fis = context.openFileInput(fileName);
        // 创建转换输出流对象
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int len = 0;
        byte[] buff = new byte[1024];

        // 循环读取数组,放到byte数组中
        while (((len = fis.read(buff)) != -1)) {
            // 读取数据并且写入ByteArrayOutputStream流当中
            bos.write(buff, 0, len);
        }
        // ByteArrayOutputStream中的数据转换成字节数组
        byte[] allData = bos.toByteArray();
        // 关闭流
        bos.close();
        fis.close();

        String dataStr = new String(allData);

        return dataStr;
    }

    /** 获取/data/data/包名/Files路径 */
    public String getFilesDir() {

        File file = context.getFilesDir();
        String absolutePath = file.getAbsolutePath();
        return absolutePath;
    }

    /** 获取/data/data/包名/CacheDir路径 */
    public String getCacheDir() {

        File file = context.getCacheDir();
        String absolutePath = file.getAbsolutePath();
        return absolutePath;
    }

    /** 获取SD卡路径 */
    public String getSdcardPath() {

        // 判断SD卡是否存在,可读可写
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().getAbsolutePath();
        } else {
            // SD卡不存在
            return null;
        }
    }

    public void writeToSdcard(String name, String data) {
        // 获取SD卡路径
        String sdPath = getSdcardPath();
        // 判断SD卡路径是否存在
        if (sdPath != null) {
            File file = new File(sdPath, name);
            try {
                if (!file.exists()) {
                    file.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(file);
                saveFile(data, fos);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("====", "SD卡不存在");
        }
    }

    private void saveFile(String content, FileOutputStream outStream)
            throws IOException {
        outStream.write(content.getBytes());// 写入数据内容
        outStream.close();// 关闭文件输出流

    }

}
package com.example.myfileupdate;

import java.io.IOException;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {

    private EditText fileEt, dataEt;
    private Button addBtn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fileEt=(EditText)findViewById(R.id.filenameEt);
        dataEt=(EditText)findViewById(R.id.dataEt);
        addBtn=(Button)findViewById(R.id.addBtn);

        addBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                String fileName=fileEt.getText().toString().trim();
                String data=dataEt.getText().toString().trim();
                if(TextUtils.isEmpty(fileName)||TextUtils.isEmpty(data)){
                    Toast.makeText(MainActivity.this, "不能为空",Toast.LENGTH_SHORT).show();
                }else{

                    FileUtil fileUtil=new FileUtil(MainActivity.this);
                    fileUtil.writeToSdcard(fileName, data);
                    //Toast.makeText(MainActivity.this, "写入成功", Toast.LENGTH_SHORT).show();

                }

            }
        });

    }



}
<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:orientation="vertical">

    <EditText
        android:id="@+id/filenameEt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="文件名" />

    <EditText 
        android:id="@+id/dataEt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="文件内容"/>

    <Button 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/addBtn"
        android:text="添加"/>

</LinearLayout>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值