简单的Internal和External文件存取

github托管地址

res/vaules/string.xml

<resources>
    <string name="app_name">Task4</string>
    <string name="file_name">文件名称:</string>
    <string name="file_content">文件内容:</string>
    <string name="btn_save_internal">存入internal文件</string>
    <string name="btn_save_external">存入external文件</string>
    <string name="btn_get_internal">获取internal文件</string>
    <string name="btn_get_external">获取external文件</string>
    <string name="internal">Internal文件内容:</string>
    <string name="extranal">Extranal文件内容:</string>
</resources>

layout/main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.liao.task4.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:layout_weight="2"
            android:text="@string/file_name" />

        <EditText
            android:id="@+id/file_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:layout_weight="2"
            android:text="@string/file_content" />

        <EditText
            android:id="@+id/file_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_save_internal"
            android:layout_width="150dp"
            android:layout_height="50dp"
            android:layout_marginLeft="30dp"
            android:text="@string/btn_save_internal" />

        <Button
            android:id="@+id/btn_save_external"
            android:layout_width="150dp"
            android:layout_height="50dp"
            android:layout_marginLeft="30dp"
            android:text="@string/btn_save_external" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:layout_weight="2"
            android:text="@string/internal" />

        <TextView
            android:id="@+id/internal_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:layout_weight="2"
            android:text="@string/extranal" />

        <TextView
            android:id="@+id/external_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_get_internal"
            android:layout_width="150dp"
            android:layout_height="50dp"
            android:layout_marginLeft="30dp"
            android:text="@string/btn_get_internal" />

        <Button
            android:id="@+id/btn_get_external"
            android:layout_width="150dp"
            android:layout_height="50dp"
            android:layout_marginLeft="30dp"
            android:text="@string/btn_get_external" />
    </LinearLayout>


</LinearLayout>


MainActivity.java

package com.example.liao.task4;

import android.content.Context;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {
    //设置目录名
    public static String DIR_NAME = "testExternal";

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //保存Internal文件形式
        Button btnSaveInternal = (Button) findViewById(R.id.btn_save_internal);
        btnSaveInternal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saveInternalFile();
            }
        });
        //获取internal文件
        Button btnGetInternal = (Button) findViewById(R.id.btn_get_internal);
        btnGetInternal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getInternalFile(MainActivity.this);
            }
        });
        // 保存External文件
        Button btnSaveExternal = (Button) findViewById(R.id.btn_save_external);
        btnSaveExternal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saveExternalFile(DIR_NAME);
            }
        });
        // 获取External文件
        Button btnGetExternal = (Button) findViewById(R.id.btn_get_external);
        btnGetExternal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getExternalFile();
            }
        });

    }


    /**********************
     * internal文件度读写  *
     **********************/


    /**
     * 保存文件
     */
    private void saveInternalFile() {
        EditText fileNameEdit = (EditText) findViewById(R.id.file_name);
        EditText fileEdit = (EditText) findViewById(R.id.file_content);
        String name = fileNameEdit.getText().toString().trim();
        String files = fileEdit.getText().toString().trim();
        TextView view = (TextView) findViewById(R.id.internal_content);
        try {
            FileOutputStream outputStream = openFileOutput(name, MODE_PRIVATE);
            outputStream.write(files.getBytes());
            outputStream.close();
            view.clearAnimation();
            view.setText(files);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取文件
     *
     * @param context
     */
    private void getInternalFile(Context context) {
        TextView internalView = (TextView) findViewById(R.id.internal_content);
        internalView.clearAnimation();
        EditText fileNameEdit = (EditText) findViewById(R.id.file_name);
        String name = fileNameEdit.getText().toString().trim();
        try {
            FileInputStream inputStream = openFileInput(name);
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            String file = new String(bytes);
            inputStream.close();
            internalView.setText(context.getFilesDir().toString() + "/" + name + ":" + file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.d("路径", context.getFilesDir().toString());

    }


    /*******************
     * external文件读写 *
     ******************/


    /**
     * 检查文件是否可写
     *
     * @return boolean
     */
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    /**
     * 检查文件是否可读
     *
     * @return boolean
     */
    public boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            return true;
        }
        return false;
    }

    /**
     * 创建文件夹
     *
     * @param dir_name
     * @return
     */
    private File setDir(String dir_name) {
        if (!isExternalStorageWritable()) {
            Log.d("ERROR", "外部存储空间加载失败");
            return null;
        }
        File dir = new File(Environment.getExternalStorageDirectory(), dir_name);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir;
    }

    /**
     * 保存文件
     *
     * @param dir_name
     */
    private void saveExternalFile(String dir_name) {
        if (!isExternalStorageWritable()) {
            Log.d("ERROR", "外部存储空间加载失败");
        } else {
            File dir = setDir(dir_name);
            EditText nameEdit = (EditText) findViewById(R.id.file_name);
            String s = nameEdit.getText().toString();
            dir = new File(dir, s);
            Log.d("文件", dir.toString());
            Log.d("test", dir.exists() + "");
            if (!dir.exists()) {
                try {
                    dir.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            EditText fileEdit = (EditText) findViewById(R.id.file_content);
            try {

                FileOutputStream outputStream = new FileOutputStream(dir, true);
                outputStream.write(fileEdit.getText().toString().getBytes());
                outputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            TextView external = (TextView) findViewById(R.id.external_content);
            external.setText(fileEdit.getText().toString());
        }
    }

    /**
     * 获取文件
     */

    private void getExternalFile() {
        if (!isExternalStorageReadable()) {
            Log.d("ERROR", "读取失败");
            Toast.makeText(this, "读取失败", Toast.LENGTH_SHORT).show();
        } else {
            EditText nameEdit = (EditText) findViewById(R.id.file_name);
            String name = nameEdit.getText().toString();
            String filePath = new File(setDir(DIR_NAME), name).toString();
            Log.d("读取文件", filePath);
            try {
                FileInputStream inputStream = new FileInputStream(filePath);

                byte[] bytes = new byte[inputStream.available()];
                inputStream.read(bytes);
                String file = new String(bytes);
                inputStream.close();
                TextView view = (TextView) findViewById(R.id.external_content);
                view.clearAnimation();
                view.setText(filePath + ":" + file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}


发表评论