Tuesday, January 6, 2015

Android Writing into Files

I had to write few contents into the file and for this, below is the code followed public void logToFile(String message)
    {
        boolean isFreshLogFile = false;
        String openStr = "-- Open Str --";
        if(fout == null)
        {
            isFreshLogFile = true;
            Log.v("RR:--","File Dir ="+getApplicationContext().getFilesDir().getPath());
            Log.v("RR:--","Cache Dir ="+getApplicationContext().getCacheDir().getPath());
            Log.v("RR:--","Ext Cache Dir ="+getApplicationContext().getExternalCacheDir().getPath());
            Log.v("RR:--","Ext Files Dir ="+getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getPath());

            File file = new File(getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS),"locationtrace.txt");
            try {
                Log.v("RR:---","creating new file");
                file.createNewFile();
                Log.v("RR:---","created new file");
            } catch (IOException e) {
                Log.v("RR:---","New file create exception");
                e.printStackTrace();
            }
            openStr = "===== Creation time ===" + new Date().toString();
            try {
                fout = new FileOutputStream(file,true) ;//openFileOutput(file.getName(),Context.MODE_APPEND);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(fout != null)
        {
            Log.v("RR:--","output stream is not null, going to write into");
            try
            {
                if(isFreshLogFile)
                {
                    fout.write(openStr.getBytes());
                }
                fout.write(message.getBytes());
//                fout.close();
            }
            catch (Exception ex)
            {
                ex.printStackTrace();;
            }
        }
    }


The logs were printed like the below 

/RR:--   ( 2056): File Dir =/data/data/mportal.mybuddy/files
V/RR:--   ( 2056): Cache Dir =/data/data/mportal.mybuddy/cache
V/RR:--   ( 2056): Ext Cache Dir =/storage/sdcard0/Android/data/mportal.mybuddy/cache
V/RR:--   ( 2056): Ext Files Dir =/storage/sdcard0/Android/data/mportal.mybuddy/files/Documents


References:

No comments:

Post a Comment