数据---File

来源:互联网 发布:安徽移动网络速度慢 编辑:程序博客网 时间:2024/06/05 01:10
Android中文件的存储操作:
  • Activity的openFileOutput()方法可以用于把数据输出到文件中
  • 创建的文件保存在/data/data/<package name>/files目录
  • 实现过程与在Java中保存数据到文件中是一样的
创建文件:
<span style="font-size:18px;color:#000000;">File file = new File("/mnt/sdcard/test");//此为内置目录,外置目录为/mnt/extsdcard/testif(!file.exists()){    try {        file.createNewFile();    } catch (IOException e) {        e.printStackTrace();    }}else {    Toast.makeText(MainActivity.this,"file already exists",Toast.LENGTH_LONG).show();}</span>
删除文件:
<span style="font-size:18px;color:#000000;">file.delete();</span>
取得内置文件目录:
<span style="font-size:18px;color:#000000;">File file = this.getFilesDir();//此目录为当前应用程序默认的数据存储目录</span>
取得外置文件目录:
<span style="font-size:18px;color:#000000;">this.getExternalFilesDir(type);</span>
该位置的数据与内置的使用一样,如果APP卸载了此目录的数据也会清除。
前提是数据在data/data/<包名>或/mnt/sdcard/Android/data/<包名>或storage/sdcard下(4.3后前两个只作为快捷方式并不实际包含数据)。否则会产生垃圾。
-----------------------------------------------------------------------------------------------------------------------------------------------------
取得内置缓存目录:
<span style="font-size:18px;color:#000000;">File file =  this.getCacheDir();//此目录是当前应用程序默认的缓存文件的存放位置</span>
可以将一些不重要的文件在此创建使用,然是如果手机内存不足时系统可能会自动删除APP中的Cache目录的数据。推荐设置缓存上限值防止系统不删用户也不删的悲剧。
取得外置缓存目录:
<span style="font-size:18px;color:#000000;">File file = this.getExternalCacheDir();</span>

------------------------------------------------------------------------------------------------------------------------------------------------------
自定义目录:
<span style="font-size:18px;color:#000000;">File file = this.getDir("icccc",MODE_PRIVATE);//自定目录/data/data/<包名>/app_icccc</span>
------------------------------------------------------------------------------------------------------------------------------------------------------

MODE_PRIVATE:
   为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下写入的内容会覆盖原文件的内容。
MODE_APPEND:
   模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE:
   用来控制其他应用是否有权限读写该文件。
MODE_WORLD_READABLE:
   表示当前文件可以被其他应用读取。
MODE_WORLD_WRITEABLE:
   表示当前文件可以被其他应用读写、写入。
Demo:
  建立布局文件:
<span style="font-size:18px;color:#000000;"><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"    tools:context="com.example.administrator.file.MainActivity">    <EditText        android:layout_width="match_parent"        android:layout_height="200dp"        android:id="@+id/edit1"        android:layout_alignParentTop="true"        android:layout_alignParentLeft="true"        android:layout_alignParentStart="true" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="写入并读写"        android:id="@+id/write"        android:background="#00000000"        android:layout_centerVertical="true"        android:layout_centerHorizontal="true" />    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="New Text"        android:id="@+id/contentValue"        android:layout_below="@+id/edit1"        android:layout_above="@+id/write"        android:layout_toLeftOf="@+id/write"        android:layout_alignParentLeft="true"        android:layout_alignParentStart="true" /></RelativeLayout></span>

  声明并实例化对象:
<span style="font-size:18px;color:#000000;">public class MainActivity extends AppCompatActivity {    EditText edit;    Button write;    TextView textView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        edit = (EditText) findViewById(R.id.edit1);        write = (Button) findViewById(R.id.write);        textView = (TextView) findViewById(R.id.contentValue);</span>
保存文件内容:
<span style="font-size:18px;color:#000000;">public void WriteFiles(String content) {        FileOutputStream fos = null;        try {            fos = openFileOutput("ic.txt", MODE_PRIVATE);            fos.write(content.getBytes());            fos.close();        } catch (IOException e) {            e.printStackTrace();        }</span>

读取文件:
<span style="font-size:18px;color:#000000;">public String readFiles(){    String content = null;    try {        FileInputStream fis = openFileInput("ic.txt");        ByteArrayOutputStream baos = new ByteArrayOutputStream()        byte[] buffer = new byte[1024];        int len = 0;        while ((len=fis.read(buffer))!=-1){             baos.write(buffer,0,len);        }        content = baos.toString();        fis.close();        baos.close();    } catch (IOException e) {        e.printStackTrace();    }    return content;}</span>

绑定按键:
<span style="font-size:18px;color:#000000;">write.setOnClickListener(new View.OnClickListener() {    @Override    public void onClick(View v) {        WriteFiles(edit.getText().toString());        textView.setText(readFiles());    }});</span>

ActivityMain.java
<span style="font-size:18px;color:#000000;">public class MainActivity extends AppCompatActivity {    EditText edit;    Button write;    TextView textView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        edit = (EditText) findViewById(R.id.edit1);        write = (Button) findViewById(R.id.write);        textView = (TextView) findViewById(R.id.contentValue);        write.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                WriteFiles(edit.getText().toString());                textView.setText(readFiles());            }        });    }    //保存文件内容    public void WriteFiles(String content) {        FileOutputStream fos = null;        try {            fos = openFileOutput("ic.txt", MODE_PRIVATE);            fos.write(content.getBytes());            fos.close();        } catch (IOException e) {            e.printStackTrace();        }    }    //读取文件    public String readFiles(){        String content = null;        try {            FileInputStream fis = openFileInput("ic.txt");            ByteArrayOutputStream baos = new ByteArrayOutputStream();            byte[] buffer = new byte[1024];            int len = 0;            while ((len=fis.read(buffer))!=-1){                 baos.write(buffer,0,len);            }            content = baos.toString();            fis.close();            baos.close();        } catch (IOException e) {            e.printStackTrace();        }        return content;    }}</span>


 

两个demo可以看看不同代码实现方式:

main_activity.xml

<span style="font-size:18px;color:#000000;"><span style="font-size:18px;color:#000000;"><?xml version="1.0" encoding="utf-8"?><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"    tools:context="com.example.administrator.project.MainActivity">    <EditText        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="input your nickname"        android:id="@+id/ip_name"        android:inputType="textPersonName"        />    <EditText        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/ip_password"        android:hint="input your password"        android:inputType="textPassword"/>    <RelativeLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/ip_password">        <CheckBox            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/save_info"            android:text="save my name and password"            android:layout_centerVertical="true" />        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/signin"            android:layout_toRightOf="@+id/save_info"            android:layout_alignParentRight="true"            android:text="SignIn"            android:onClick="OnWrite"/>    </RelativeLayout></LinearLayout></span>


ActivityMain.java

<span style="font-size:18px;color:#000000;"><span style="font-size:18px;color:#000000;">package com.example.administrator.project;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.CheckBox;import android.widget.EditText;import java.io.BufferedInputStream;import java.io.BufferedReader;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.InputStreamReader;public class MainActivity extends AppCompatActivity {    private EditText ip_name, ip_password;    private Button signin;    private CheckBox save_info;    private String text;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        ip_name = (EditText) findViewById(R.id.ip_name);        ip_password = (EditText) findViewById(R.id.ip_password);        signin = (Button) findViewById(R.id.signin);        save_info = (CheckBox) findViewById(R.id.save_info);        Readout();    }    public void Readout() {        File file = new File(getFilesDir(),"info.txt");        //File file = new File(getCacheDir(),"info.txt");        if (file.exists()) {            try {                FileInputStream fis = new FileInputStream(file);                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis));                text = bufferedReader.readLine();                String[] s = text.split("##");                ip_name.setText(s[0]);                ip_password.setText(s[1]);                bufferedReader.close();                fis.close();            } catch (FileNotFoundException e) {                e.printStackTrace();            } catch (IOException e) {                e.printStackTrace();            }        }    }    public void OnWrite(View view){        String ipName = ip_name.getText().toString();        String ipPassword = ip_password.getText().toString();        if(save_info.isChecked()) {            File file = new File(getFilesDir(),"info.txt");            //File file = new File(getCacheDir(),"info.txt");            try {                FileOutputStream fos = new FileOutputStream(file);                fos.write((ipName+"##"+ipPassword).getBytes());                fos.close();            } catch (FileNotFoundException e) {                e.printStackTrace();            } catch (IOException e) {                e.printStackTrace();            }        }    }}</span>

外部储存读写加权限写File file = new File("sdcard/info.txt"){由于厂商原因可能不能的到真实sdcard路径,推荐使用API获取路径};或File file = new File(Environment.getExternalStorgeDirectory(),"info.txt");后者为安卓提供的API。
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {    File file = new File(Environment.getExternalStorageDirectory(), "info.txt");}
读写前先判断sdcard是否可用
sdacrd常用的几种状态:
  • MEDIA_CHECKING sdcard正在准备
  • MEDIA_REMOVED 没有sdcard
  • MEDIA_MOUNTED sdcard以挂载
  • MEDIA_UNMOUNTED sdcard存在但还未挂载
  • MEDIA_UNKNOWN 不能识别sdcard


0 0
原创粉丝点击