Android/安卓开发两句代码写文件到内存

根据网上找到的代码修改而成,对原作者表示感谢。因为找不到出处链接,此处未标明。使用这个类可以方便的实现将文本信息写入存储或者SD卡。整个使用过程只需要两句代码。

新建一个class文件 WriteToFile.java

package com.bm.cavell.batterymeasurement.utils;//换成你自己的包名

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
 * Created by Cavell on 2018/4/23.
 */
public class WriteToFile {
    private static String TAG = "WriteToFile";
    private static String filePath = null;

    public static void init(Context context,String fileName){
        filePath = getFilePath(context) + fileName;//此处传入的filename 应该是类似 /BlueTooth/record1
    }

    private static String getFilePath(Context context) {

        if (Environment.MEDIA_MOUNTED.equals(Environment.MEDIA_MOUNTED) ||
                !Environment.isExternalStorageRemovable()) {//如果外部储存可用
            return context.getExternalFilesDir(null).getPath();//获得外部存储路径,默认路径为 /storage/emulated/0/Android/data/com.bm.cavell.batterymeasurement/files/Logs/log_2017-09-14_16-15-09.log
        } else {
            return context.getFilesDir().getPath();//直接存在/data/data里,非root手机是看不到的
        }
    }

    public static void writeToFile(String msg) {

        if (null == filePath) {
            Log.e(TAG, "filePath == null ,未初始化WriteToFile");
            return;
        }

        String text = msg + "\n";//log日志内容,可以自行定制

        //如果父路径不存在
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();//创建父路径
        }

        FileOutputStream fos = null;//FileOutputStream会自动调用底层的close()方法,不用关闭
        BufferedWriter bw = null;
        try {

            fos = new FileOutputStream(filePath + ".txt", true);//这里的第二个参数代表追加还是覆盖,true为追加,flase为覆盖
            bw = new BufferedWriter(new OutputStreamWriter(fos));
            bw.write(text);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bw != null) {
                    bw.close(); //关闭缓冲流
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

调用该类只需要在你的MainActivity中初始化一下即可,如:

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

        WriteToFile.init(getContext(),"/BleData/ble");//初始化,第一句代码
    }

然后在你需要写内容到SD卡的地方调用

 WriteToFile.writeToFile(“你要输入的内容放在这里");//第二句代码

猜你喜欢

转载自blog.csdn.net/chance00/article/details/80056794