How to include a static log file into an Android a

2019-08-28 02:04发布

I want to include a static log file within my app. Whenever the user starts the app, a time with extra information will be appended to that file. At the beginning, I thought storing the file into assets folder or raw folder would be the solution, but then I looked into android documentations where it states:

Tip: If you want to save a static file in your application at compile time, save the file in your project res/raw/ directory. You can open it with openRawResource(), passing the R.raw. resource ID. This method returns an InputStream that you can use to read the file (but you cannot write to the original file).

How can I solve this problem?

EDIT:

I want the log file not to be removed on closing the app.

3条回答
唯我独甜
2楼-- · 2019-08-28 02:51

Well i don't see the problem, your user will open the app and it will be runtime and you can write what ever you want to what ever file. So this tip doesn't apply to you.

查看更多
Animai°情兽
3楼-- · 2019-08-28 02:55

Here is the solution:

private void writeLog(String s)
{
    String FILENAME = "log.txt";
    FileOutputStream fos = null;
    try
    {
        fos = openFileOutput(FILENAME, Context.MODE_APPEND);
        fos.write(s.getBytes());
    }
    catch(FileNotFoundException e){}
    catch(IOException e){}
    finally
    {
        try
        {
            fos.close();
        }
        catch(IOException e){}
    }
}
private void readLog(EditText logs)
{
    String FILENAME = "log.txt";
    FileInputStream in = null;
    try
    {
        in = openFileInput(FILENAME);
    }
    catch(IOException e1){}
    try
    {
        byte[] buffer = new byte[4096]; // Read 4K characters at a time.
        int len;
        logs.setText("");
        while((len = in.read(buffer)) != -1)
        {
            String s = new String(buffer, 0, len);
            logs.append(s);
        }
    }
    catch(IOException e){}
    finally
    {
        try
        {
            if(in != null) in.close();
        }
        catch(IOException e){}
    }
}
查看更多
Root(大扎)
4楼-- · 2019-08-28 02:57

Instead of including the log file with the app you should create it on first launch.

There's more information How to create a file in Android? on creating a file.

查看更多
登录 后发表回答