android学习笔记五—android的存储2 文件的读取与写入

一,data/data/{包名}/files文件夹下的文件读取和写入

在此目录下并不需要做太多处理,只要知道文件名就可以进行读写

//读取文件函数
public String readInStream(Context context,String FileName) throws IOException{
        FileInputStream in=context.openFileInput(FileName);
             //获取文件长度
        int length=in.available();
        byte [] bytes = new byte[length];
        try{
            in.read(bytes);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String str="";
        //解码,需要选择文件对应的格式,否则可能出现乱码等问题
        str = EncodingUtils.getString(bytes, "UTF-8"); 
        in.close();

        return str;
    }

    //写入文件函数

    public void writeInStream(Context context,int mode,String WantWrite,String FileName) throws IOException{
         FileOutputStream out=context.openFileOutput(FileName, mode);
         out.write(WantWrite.getBytes());
         out.close();
    }

二、读取resource/raw文件夹下的文件
需要通过getResources来获得文件

public String readrawInStream(Context context) throws IOException{
        InputStream in=context.getResources().openRawResource(R.raw.text);
        int length=in.available();
        byte [] bytes = new byte[length];
        try{
            in.read(bytes);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String str="";
        str = EncodingUtils.getString(bytes, "UTF-8"); 
        in.close();

        return str;
    }

三,读写SD卡中文件
SD卡中的文件因为存于SD中,所以处理上稍有不同,需要先判断机器上是否插有SD卡,并且是否具有访问权限,之后才能访问文件,下面来介绍一下完整步骤
1.设置SD卡访问权限,毋庸置疑,没有权限是不可能访问成功的,所以需要在入口xml中注册权限,注册方法如代码:

<!-- SD卡创建或删除权限 -->
<uses-permission android:name="android.permission.MOUNT_FORMAT_FILESYSTEMS"/>
<!-- SD卡写入权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

2.访问之前需要判断机器是否具有sd卡条件,没有自然就不能访问

if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){}

3.获取SD卡目录,并创建文件

if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            //获取sD卡目录
            File SdCarddirectory=Environment.getExternalStorageDirectory();
            //创建文件
            File Savefilename=new File(SdCarddirectory,fileName);
            try{
                //创建新文件
                Savefilename.createNewFile();   
            }catch(IOException e){
                Toast.makeText(FileDemo.this, e.getMessage(),Toast.LENGTH_LONG).show();
            }
            FileOutputStream out=new FileOutputStream(Savefilename);
            out.write(wantWrite.getBytes());
            out.close();
        }else{
            Toast.makeText(FileDemo.this, "no such file",Toast.LENGTH_LONG).show();
        }

文件操作示例代码

FileDemo.java

package com.example.ui_demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import org.apache.http.util.EncodingUtils;

import android.app.Activity;
import android.app.TabActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.TabHost.OnTabChangeListener;

public class FileDemo extends Activity {
    private String []str={"Mode_Private","Mode_Append","Mode_WorldRead","Mode_WorldWrite"};
    private Spinner sp;
    private ArrayAdapter<String> arrayAdapter;
    private int mySelected=-1;
    private Button write;
    private Button read;
    private Button writeSD;
    private Button readSD;
    private Button rawread;
    private SharedPreferences share;
    private EditText name;
    private EditText id;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_demo);
        sp=(Spinner)this.findViewById(R.id.typeFile);
        write=(Button)this.findViewById(R.id.writefile);
        read=(Button)this.findViewById(R.id.readfile);
        writeSD=(Button)this.findViewById(R.id.writeSD);
        readSD=(Button)this.findViewById(R.id.readSD);
        rawread=(Button)this.findViewById(R.id.rawread);
        arrayAdapter=new ArrayAdapter<String>(FileDemo.this,android.R.layout.simple_spinner_item, str);
        //arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp.setAdapter(arrayAdapter);
        sp.setOnItemSelectedListener(new OnItemSelectedListener(){

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int position, long id) {
                // TODO Auto-generated method stub
                String str=arg0.getItemAtPosition(position).toString();
                if(str=="Mode_Private"){
                   mySelected=Context.MODE_PRIVATE;
                }else if(str=="Mode_Append"){
                    mySelected=Context.MODE_APPEND;
                }else if(str=="Mode_WorldRead"){
                    mySelected=Context.MODE_WORLD_READABLE;
                }else if(str=="Mode_WorldWrite"){
                    mySelected=Context.MODE_WORLD_WRITEABLE;
                }else{
                    mySelected=-1;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
                mySelected=-1;
            }

        });
        Mybutton m=new Mybutton();
        write.setOnClickListener(m);
        read.setOnClickListener(m);
        rawread.setOnClickListener(m);
        readSD.setOnClickListener(m);
        writeSD.setOnClickListener(m);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.file_demo, 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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    //读取文件函数

    public String readInStream(Context context,String FileName) throws IOException{
        FileInputStream in=context.openFileInput(FileName);
        int length=in.available();
        byte [] bytes = new byte[length];
        try{
            in.read(bytes);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String str="";
        str = EncodingUtils.getString(bytes, "UTF-8"); 
        in.close();

        return str;
    }
    public String readrawInStream(Context context) throws IOException{
        InputStream in=context.getResources().openRawResource(R.raw.text);
        int length=in.available();
        byte [] bytes = new byte[length];
        try{
            in.read(bytes);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String str="";
        str = EncodingUtils.getString(bytes, "UTF-8"); 
        in.close();

        return str;
    }
    //写入SD卡
    public void writeSDInStream(String fileName,String wantWrite) throws IOException{
        //判断SD卡是否存在
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            //获取sD卡目录
            File SdCarddirectory=Environment.getExternalStorageDirectory();
            //创建文件
            File Savefilename=new File(SdCarddirectory,fileName);
            try{
                Savefilename.createNewFile();   
            }catch(IOException e){
                Toast.makeText(FileDemo.this, e.getMessage(),Toast.LENGTH_LONG).show();
            }
            FileOutputStream out=new FileOutputStream(Savefilename);
            out.write(wantWrite.getBytes());
            out.close();
        }else{
            Toast.makeText(FileDemo.this, "no such file",Toast.LENGTH_LONG).show();
        }
    }
    //读取SD卡
    public String readSDInStream(String fileName) throws IOException{
        //判断SD卡是否存在
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            //获取sD卡目录
            File SdCarddirectory=Environment.getExternalStorageDirectory();
            File readfile=new File(SdCarddirectory,fileName);
            FileInputStream in = new FileInputStream(readfile);
            int length=in.available();
            byte []bytes=new byte[length];
            in.read(bytes);
            String str=EncodingUtils.getString(bytes, "UTF-8");         
            return str;
        }else{
            return "fail";
        }
    }

    //写入文件函数

    public void writeInStream(Context context,int mode,String WantWrite,String FileName) throws IOException{
         FileOutputStream out=context.openFileOutput(FileName, mode);
         out.write(WantWrite.getBytes());
         out.close();
    }


    public class Mybutton implements OnClickListener{

        @Override
        public void onClick(View vi) {
            // TODO Auto-generated method stub
            if(vi==write){

                if(mySelected!=-1){
                Context context=FileDemo.this;
                try {
                    //context.openFileOutput("text.txt",Context.MODE_APPEND);
                    writeInStream(FileDemo.this,Context.MODE_APPEND,"lianggong zhazha","text.txt");
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                }else{
                    Toast.makeText(FileDemo.this, "未选择type",Toast.LENGTH_LONG).show();
                }
            }else if(vi==read){
                if(mySelected!=-1){
                    Context context=FileDemo.this;
                    try {
                        //context.openFileOutput("text.txt",Context.MODE_APPEND);

                        String str="";
                        str = readInStream(FileDemo.this,"text.txt"); 
                        Toast.makeText(FileDemo.this, str,Toast.LENGTH_LONG).show();
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }else{
                    Toast.makeText(FileDemo.this, "未选择type",Toast.LENGTH_LONG).show();
                }
            }else if(vi==rawread){
                try {
                    //context.openFileOutput("text.txt",Context.MODE_APPEND);               
                    String str="";
                    str = readrawInStream(FileDemo.this); 
                    Toast.makeText(FileDemo.this, str,Toast.LENGTH_LONG).show();
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }else if(vi==readSD){
                String str="";
                try {
                    str=readSDInStream("text.txt");
                    Toast.makeText(FileDemo.this, str,Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }else if(vi==writeSD){
               try {
                writeSDInStream("text.txt","lianggong zhazha gang");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }
        }

    }
}

FileDemo.xml

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

    <TextView
        android:id="@+id/NameFile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name:" >

    </TextView>

    <EditText
        android:id="@+id/editNameFile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="清输入数值" >

    </EditText>
        <TextView
        android:id="@+id/idFile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="id:" >

    </TextView>

    <EditText
        android:id="@+id/editidFile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="清输入数值" >

    </EditText>

    <Spinner
        android:id="@+id/typeFile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:spinnerMode="dropdown" >

    </Spinner>

    <TableLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    <TableRow >
           <Button
        android:id="@+id/rawread"
        android:text="读取raw"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </Button>
    </TableRow>
     <TableRow >
    <Button  
        android:id="@+id/writefile"
        android:text="写入"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </Button>
     </TableRow>
      <TableRow>
     <Button  
        android:id="@+id/readfile"
        android:text="读取"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </Button>
     </TableRow>
          <TableRow >
    <Button  
        android:id="@+id/writeSD"
        android:text="写入SD"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </Button>
     </TableRow>
      <TableRow>
     <Button  
        android:id="@+id/readSD"
        android:text="读取SD"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </Button>
     </TableRow>
    </TableLayout>



</LinearLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值