Creating and Storing Log File on device in Android

前端 未结 2 1679
难免孤独
难免孤独 2020-12-24 14:07

I am planning to automate the testing of an application by creating a log to store some results of execution of the app and latter on parse it using a piece of python code a

2条回答
  •  温柔的废话
    2020-12-24 14:56

    I used a very simple approach to write String messages to the log file by creating a FileWriter object.

        public static BufferedWriter out;
            private void createFileOnDevice(Boolean append) throws IOException {
                    /*
                     * Function to initially create the log file and it also writes the time of creation to file.
                     */
                    File Root = Environment.getExternalStorageDirectory();
                    if(Root.canWrite()){
                         File  LogFile = new File(Root, "Log.txt");
                         FileWriter LogWriter = new FileWriter(LogFile, append);
                         out = new BufferedWriter(LogWriter);
                         Date date = new Date();
                         out.write("Logged at" + String.valueOf(date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "\n")); 
                         out.close();
    
                }
            }
    

    Now the function to write a new message to the log file.

        public void writeToFile(String message){
                try {
                    out.write(message+"\n");
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
    

提交回复
热议问题