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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章