黎活明8天快速掌握android视频教程--12_文件的保存与读取

1、当前是把文件保存当前手机的app的data目录下

我们来看看操作保存文件的业务类

package contract.test.savafileapplication;

import android.content.Context;

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


public class FileService {
    private Context context;

    public FileService(Context context) {
        this.context = context;
    }

    public   void saveFile(String fileName, String fileContext) throws Exception {
       FileOutputStream fileOutputStream = context.openFileOutput(fileName,Context.MODE_WORLD_READABLE);
       fileOutputStream.write(fileContext.getBytes());
       fileOutputStream.close();
   }

    public  String readFile(String filename) throws IOException {

        FileInputStream fileInputStream = context.openFileInput(filename);

        byte[] bytes = new byte[1024];
        ByteArrayOutputStream  byteArrayOutputStream = new ByteArrayOutputStream();
        /*byte是基本数据类型  如int类型
          Byte是byte的包装类*/
        int len = 0;
        while ((len = fileInputStream.read(bytes))!=-1)
        {

           byteArrayOutputStream.write(bytes,0,len);
        }
        byteArrayOutputStream.close();
        fileInputStream.close();
        String str = new String(byteArrayOutputStream.toString());
        return  str;
    }
}
openFileInput保存文件有四种类型:

openFileOutput(“a.txt”,Context.MODE_WORLD_READABLE)方法第一个参数是文件名,若不存在这个文件,则自动创建,第二个参数是操作模式共四种:

Context.MODE_PRIVATE    =  0
Context.MODE_APPEND    =  32768
Context.MODE_WORLD_READABLE =  1
Context.MODE_WORLD_WRITEABLE =  2

Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中。可以使用Context.MODE_APPEND
Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件。
MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。
如果希望文件被其他应用读和写,可以传入:
openFileOutput(“itcast.txt”, Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

activity的代码是:

package contract.test.savafileapplication;

import android.app.Activity;
import android.os.Bundle;
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 android.widget.Toast;

import java.io.IOException;


public class MyActivity extends Activity {
    private Button save , show;
    private EditText filename, filecontext;
    private TextView showContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        save = (Button)this.findViewById(R.id.saveButton);
        show = (Button)this.findViewById(R.id.showButton);
        filename = (EditText)this.findViewById(R.id.fileName_ET);
        filecontext = (EditText)this.findViewById(R.id.saveContext_ET);

        showContext = (TextView)this.findViewById(R.id.showConTextView);

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              String name =  filename.getText().toString();
              String context = filecontext.getText().toString();
              FileService fileService = new FileService(getApplicationContext());
                try {
                    fileService.saveFile(name,context);
                    Toast.makeText(getApplicationContext(),"文件保存成功!",Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(),"文件保存失败!",Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
            }
        });
        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              FileService fileService = new FileService(getApplicationContext());
                String name =  filename.getText().toString();
                try {
                    String str = fileService.readFile(name);
                    Toast.makeText(getApplicationContext(),"文件读取成功!",Toast.LENGTH_LONG).show();
                    showContext.setText(str);
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),"文件读取失败!",Toast.LENGTH_LONG).show();
                }
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.my, 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);
    }
}

xml的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="请输入要保存的文件名:"
        />
    <EditText
        android:id="@+id/fileName_ET"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:hint="请输入要保存的文件名!"
        />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="请您输入要保存的内容:"
        />
    <EditText
        android:id="@+id/saveContext_ET"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="请您在此处输入文件内容!"
        />
    <Button
        android:id="@+id/saveButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="save"
        />
    <Button
        android:id="@+id/showButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="show"
        />
    <TextView
        android:id="@+id/showConTextView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>

 

 

 

posted on 2017-04-24 15:48  luzhouxiaoshuai  阅读(205)  评论(0编辑  收藏  举报

导航