Android 数据存储与IO (二)

2.SD卡读写操作


1读写sd卡首先得添加读写权限

技术分享2.建一个布局文件,用来接收和展示数据

<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" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <Button
        android:id="@+id/buttonWrite"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="写入数据"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />
    <EditText
        android:id="@+id/edit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/buttonWrite"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <Button
        android:id="@+id/buttonReade"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="读取数据"
        android:layout_below="@+id/edit"
        android:layout_alignLeft="@+id/buttonWrite"
        android:layout_alignStart="@+id/buttonWrite"
        android:layout_marginTop="73dp" />
    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="yu"
        android:textSize="20sp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="167dp" />

</RelativeLayout>

3.

package xiaocool.net.sdtest;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;


public class MainActivity extends ActionBarActivity {

    private final  String FILE_NAME="/xiaocool.bin";

    private Button write,read;
    private EditText editText;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        write=(Button)this.findViewById(R.id.buttonWrite);
        read=(Button)this.findViewById(R.id.buttonReade);
        editText=(EditText)this.findViewById(R.id.edit);
        textView=(TextView)this.findViewById(R.id.textview);

        write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Write(editText.getText().toString());
                editText.setText("");
            }
        });
        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText(Read());
            }
        });

    }
    //往sd卡写入数据的方法
    private void Write(String content){
    try{
        //如果手机插入了sd卡,而且 具有访问sd卡的权限
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){

            //获取sd卡的目录
            File sdCradDir=Environment.getExternalStorageDirectory();
            File targetFile=new File(sdCradDir.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();
        }
    }
    //从sd卡读取数据
    private String Read(){
       try {
           if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
               File sdCardDir=Environment.getExternalStorageDirectory();
               //获取制定文件对应的输入流
               FileInputStream file=new FileInputStream(sdCardDir.getCanonicalPath()+FILE_NAME);
               //将制定的输入流包装成BufferReader
               BufferedReader br=new BufferedReader(new InputStreamReader(file));
               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;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


本文出自 “阿乾-在路上” 博客,请务必保留此出处http://xiaocool.blog.51cto.com/1593956/1622746

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。