Android / Android develops two lines of code to write files to memory

Posted by aneuryzma on Thu, 02 Apr 2020 21:41:24 +0200

Based on the code found on the Internet, thanks to the original author. The source link was not found and is not indicated here. This class can be used to write text information to memory or SD card. Only two sentences of code are needed in the whole process.

Create a new class file WriteToFile.java

package com.bm.cavell.batterymeasurement.utils;//Change to your own bag name

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;//The filename passed in here should be similar to / BlueTooth/record1
    }

    private static String getFilePath(Context context) {

        if (Environment.MEDIA_MOUNTED.equals(Environment.MEDIA_MOUNTED) ||
                !Environment.isExternalStorageRemovable()) {//If external storage is available
            return context.getExternalFilesDir(null).getPath();//Get the external storage path. The default path is / storage / simulated / 0 / Android / data / com.bm.cavell.batterymeasurement/files/logs/log ﹣ 2017-09-14 ﹣ 16-15-09.log
        } else {
            return context.getFilesDir().getPath();//Directly in / data/data, non root phones cannot be seen
        }
    }

    public static void writeToFile(String msg) {

        if (null == filePath) {
            Log.e(TAG, "filePath == null ,uninitialized WriteToFile");
            return;
        }

        String text = msg + "\n";//Log log content, which can be customized by yourself

        //If the parent path does not exist
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();//Create parent path
        }

        FileOutputStream fos = null;//FileOutputStream will automatically call the underlying close() method without closing
        BufferedWriter bw = null;
        try {

            fos = new FileOutputStream(filePath + ".txt", true);//The second parameter here represents append or overwrite. true is append, and flash is overwrite
            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(); //Close buffer stream
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

To call this class, you only need to initialize it in your MainActivity, such as:

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

        WriteToFile.init(getContext(),"/BleData/ble");//Initialization, first code
    }

Then call where you need to write to the SD card

 WriteToFile.writeToFile("put what you want to input here"); / / the second code

Topics: Java Android