在Android中的设备上创建和存储日志文件

时间:2021-05-24 16:52:49

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 and plot a graph.

我计划通过创建一个日志来自动化应用程序的测试,该日志存储应用程序的一些执行结果,后者使用一段python代码解析它并绘制图形。

The application is a WiFi fingerprinter i.e it collects info such as mac id, rss(recieved signal strength and rank(normalized rss) about the wifi devices in the surrounding environment. So to test this application I would have to take it to the location and record the results(as of now manually). So logcat wouldn't serve the purpose.

该应用程序是一个WiFi指纹识别器,即它收集有关周围环境中的wifi设备的信息,如mac id,rss(收到的信号强度和等级(标准化的rss)。所以为了测试这个应用程序,我必须把它带到位置和记录结果(截至现在手动)。所以logcat不能达到目的。

Automation requires 1. Storing the log in the device 2. Access to the log file in the system through usb

自动化要求1.将日志存储在设备中2.通过USB访问系统中的日志文件

Format of the Log file:

日志文件的格式:

Snapshot: 1
Fingerprint: 1, Rank: 0.23424, Boolean: true
Fingerprint: 2, Rank: 0.42344, Boolean: false
Fingerprint: 3, Rank: 0.23425, Boolean: true

Snapshot: 2
Fingerprint: 1, Rank: 0.75654, Boolean: false
Fingerprint: 2, Rank: 0.23456, Boolean: true
Fingerprint: 3, Rank: 0.89423, Boolean: true 

................

Now I know there are basically 3 approaches for persistent storage(SharedPrefs wouldn't suit this scenario anyway). I tried Internal Storage, but even after setting the mode of the file as MODE_WORLD_READABLE it was impossible to read the file using Device File Explorer in Eclipse.

现在我知道持久存储基本上有3种方法(无论如何,SharedPrefs都不适合这种情况)。我尝试了内部存储,但即使将文件模式设置为MODE_WORLD_READABLE,也无法使用Eclipse中的Device File Explorer读取文件。

I am still wary of using external storage for storing the log. Any tutorial on how to write to a file in usb of the device will definitely help.

我仍然担心使用外部存储来存储日志。任何有关如何在设备的USB中写入文件的教程肯定会有所帮助。

I thought of structuring the data to be stored so as to use SQLite for storage. But this establishing many unnecessary relations(foreign and domestic) between data and make it complex. If there is no way around, then here be dragons.

我想构建要存储的数据,以便使用SQLite进行存储。但这在数据之间建立了许多不必要的关系(国内和国内)并使其变得复杂。如果没有办法,那么这里就是龙。

Basically I want to write to a file(easier I suppose) in the device and latter on read it in my system by connecting to it via usb. Any help on how to do it would be much appreciated.

基本上我想写一个文件(我想更容易)在设备中,后者在我的系统中通过usb连接到它来读取它。如何做任何帮助将不胜感激。

2 个解决方案

#1


11  

Wary or not, External Storage still may be the only way to go. Without root access on the device, you can't really get at anything "Internal" unless you're going to be okay with reading within an application on the device. The docs provide pretty solid guidelines for where to create external files, and if you are using API Level 8 or higher, there are a couple of extra functions that can be used. I'm sure you know this page, but here it is anyway: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal

不管是否谨慎,外部存储仍然是唯一的出路。如果没有设备上的root访问权限,除非你在设备上的应用程序内阅读,否则你无法真正获得任何“内部”。这些文档为创建外部文件的位置提供了非常可靠的指导,如果您使用的是API级别8或更高级别,则可以使用一些额外的功能。我确定你知道这个页面,但无论如何它在这里:http://developer.android.com/guide/topics/data/data-storage.html#filesExternal

If you're in need of any file io example code... I think I could dig some up...

如果你需要任何文件io示例代码...我想我可以挖掘一些......

EDIT - I would start by following the guidelines in the above docs to first confirm the state of the storage. I unfortunately don't have any experience with appending a file in Java, so someone else would definitely be more qualified to answer. This doesn't cover appending, but I have a backup routine in one of my personal apps that looks something like this.

编辑 - 我将首先遵循上述文档中的指南,首先确认存储的状态。遗憾的是,我没有任何使用Java附加文件的经验,所以其他人肯定更有资格回答。这不包括附加内容,但我在我的一个个人应用程序中有一个备份例程,看起来像这样。

    File backupPath = Environment.getExternalStorageDirectory();

    backupPath = new File(backupPath.getPath() + "/Android/data/com.maximusdev.bankrecord/files");

    if(!backupPath.exists()){
        backupPath.mkdirs();
    }

    FileOutputStream fos;
    try {
        fos = new FileOutputStream(backupPath.getPath() + "/recordsbackup.txt");

        if(okaytowrite){
            for(int i = 0; i < count; ++i){
                entry = adapter.getItem(i);
                fos.write(entry.toString().getBytes());
                fos.write("\n".getBytes());
                fos.write(String.valueOf(entry.dateTime).getBytes());
                fos.write("\n".getBytes());
                fos.write(String.valueOf(entry.sign).getBytes());
                fos.write("\n".getBytes());
                fos.write(String.valueOf(entry.cleared).getBytes());
                fos.write("\n".getBytes());
                fos.write(String.valueOf(entry.transDate).getBytes());
                fos.write("\n".getBytes());
                fos.write(entry.category.getBytes());
                fos.write("\n".getBytes());
            }
        }
        fos.close();

        Toast.makeText(this, "Backup Complete", Toast.LENGTH_SHORT).show();

    } catch (FileNotFoundException e) {

        e.printStackTrace();

        AlertDialog.Builder delmessagebuilder = new AlertDialog.Builder(this);

        delmessagebuilder.setCancelable(false);

        delmessagebuilder.setMessage("File Access Error");

        delmessagebuilder.setNeutralButton("Okay", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();
            }
        });

        delmessagebuilder.create().show();

    } catch (IOException e) {

        e.printStackTrace();

        AlertDialog.Builder delmessagebuilder = new AlertDialog.Builder(this);

        delmessagebuilder.setCancelable(false);

        delmessagebuilder.setMessage("File Access Error");

        delmessagebuilder.setNeutralButton("Okay", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();
            }
        });

        delmessagebuilder.create().show();
    }

Once I'm ready to write, I'm pulling a custom object (entry) out of an ArrayAdapter (adapter) and converting field valuse to strings and using getBytes() to pass to the FileOutputStream write function. I've done some research and there are quite a few other options for file writing in Java/Android... the FileWriter Class for instance, so it bears further research.

一旦我准备好编写,我就从ArrayAdapter(适配器)中提取自定义对象(条目)并将字段值转换为字符串,并使用getBytes()传递给FileOutputStream写入函数。我已经做了一些研究,并且在Java / Android中有很多其他的文件编写选项...例如FileWriter Class,因此需要进一步研究。

#2


12  

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

我使用一种非常简单的方法通过创建FileWriter对象将String消息写入日志文件。

    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();
            }

#1


11  

Wary or not, External Storage still may be the only way to go. Without root access on the device, you can't really get at anything "Internal" unless you're going to be okay with reading within an application on the device. The docs provide pretty solid guidelines for where to create external files, and if you are using API Level 8 or higher, there are a couple of extra functions that can be used. I'm sure you know this page, but here it is anyway: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal

不管是否谨慎,外部存储仍然是唯一的出路。如果没有设备上的root访问权限,除非你在设备上的应用程序内阅读,否则你无法真正获得任何“内部”。这些文档为创建外部文件的位置提供了非常可靠的指导,如果您使用的是API级别8或更高级别,则可以使用一些额外的功能。我确定你知道这个页面,但无论如何它在这里:http://developer.android.com/guide/topics/data/data-storage.html#filesExternal

If you're in need of any file io example code... I think I could dig some up...

如果你需要任何文件io示例代码...我想我可以挖掘一些......

EDIT - I would start by following the guidelines in the above docs to first confirm the state of the storage. I unfortunately don't have any experience with appending a file in Java, so someone else would definitely be more qualified to answer. This doesn't cover appending, but I have a backup routine in one of my personal apps that looks something like this.

编辑 - 我将首先遵循上述文档中的指南,首先确认存储的状态。遗憾的是,我没有任何使用Java附加文件的经验,所以其他人肯定更有资格回答。这不包括附加内容,但我在我的一个个人应用程序中有一个备份例程,看起来像这样。

    File backupPath = Environment.getExternalStorageDirectory();

    backupPath = new File(backupPath.getPath() + "/Android/data/com.maximusdev.bankrecord/files");

    if(!backupPath.exists()){
        backupPath.mkdirs();
    }

    FileOutputStream fos;
    try {
        fos = new FileOutputStream(backupPath.getPath() + "/recordsbackup.txt");

        if(okaytowrite){
            for(int i = 0; i < count; ++i){
                entry = adapter.getItem(i);
                fos.write(entry.toString().getBytes());
                fos.write("\n".getBytes());
                fos.write(String.valueOf(entry.dateTime).getBytes());
                fos.write("\n".getBytes());
                fos.write(String.valueOf(entry.sign).getBytes());
                fos.write("\n".getBytes());
                fos.write(String.valueOf(entry.cleared).getBytes());
                fos.write("\n".getBytes());
                fos.write(String.valueOf(entry.transDate).getBytes());
                fos.write("\n".getBytes());
                fos.write(entry.category.getBytes());
                fos.write("\n".getBytes());
            }
        }
        fos.close();

        Toast.makeText(this, "Backup Complete", Toast.LENGTH_SHORT).show();

    } catch (FileNotFoundException e) {

        e.printStackTrace();

        AlertDialog.Builder delmessagebuilder = new AlertDialog.Builder(this);

        delmessagebuilder.setCancelable(false);

        delmessagebuilder.setMessage("File Access Error");

        delmessagebuilder.setNeutralButton("Okay", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();
            }
        });

        delmessagebuilder.create().show();

    } catch (IOException e) {

        e.printStackTrace();

        AlertDialog.Builder delmessagebuilder = new AlertDialog.Builder(this);

        delmessagebuilder.setCancelable(false);

        delmessagebuilder.setMessage("File Access Error");

        delmessagebuilder.setNeutralButton("Okay", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();
            }
        });

        delmessagebuilder.create().show();
    }

Once I'm ready to write, I'm pulling a custom object (entry) out of an ArrayAdapter (adapter) and converting field valuse to strings and using getBytes() to pass to the FileOutputStream write function. I've done some research and there are quite a few other options for file writing in Java/Android... the FileWriter Class for instance, so it bears further research.

一旦我准备好编写,我就从ArrayAdapter(适配器)中提取自定义对象(条目)并将字段值转换为字符串,并使用getBytes()传递给FileOutputStream写入函数。我已经做了一些研究,并且在Java / Android中有很多其他的文件编写选项...例如FileWriter Class,因此需要进一步研究。

#2


12  

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

我使用一种非常简单的方法通过创建FileWriter对象将String消息写入日志文件。

    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();
            }