1802 file record daily log

Keywords: Android network Java

Download the demo of this article: File logging demo

There will be a lot of information in the daily operation of app. Generally, we upload the information in daily use to the server, but this method can't be used without network environment. The solution is that we can save these records in a local file and upload them to the server when there is a network.

1. Add file read / write permission

Android 6.0 and above requires dynamic access to read and write files, which should be noted. This example is a simple illustration. It uses static registration directly and can only be used in systems under 6.0.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2. Using java to read and write input and output streams

Write code:

/**
*  File path
*/
public static final String ROOT_PATH = Environment
        .getExternalStorageDirectory() + File.separator + "Mhwang";
public static final String ERROR_DIR_PATH = ROOT_PATH + File.separator + "ErrorNote";

/** Log
* @param message
*/
public static void writeNote(String message){
    // Path to save exception information
    String path = ERROR_DIR_PATH + File.separator + "note"+DateUtil.getCurrentDate() + ".txt";
    String occurTime = DateUtil.getCurrentTime();
    File file = new File(path);
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    try {
        // Save log file
        Writer writer = new FileWriter(file, true);
        writer.write(occurTime + message+"\n");
        writer.flush();
        writer.close();
    }catch (Exception e){

    }
}

Read code:

/** Read data
* @param path
* @return
*/
public static String read(String path){
    BufferedReader reader = null;
    StringBuilder builder = new StringBuilder();
    try {
        String str = null;
        reader = new BufferedReader(new FileReader(new File(path)));
        while ((str = reader.readLine()) != null ){
            builder.append(str);
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }finally {
        if (reader != null){
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return builder.toString();
}

Example effect:

Posted by zman on Thu, 30 Apr 2020 17:21:28 -0700