Android Writing Logs to text File

android

Solution

Hope this can help...

public void appendLog(String text)
{       
   File logFile = new File("sdcard/log.file");
   if (!logFile.exists())
   {
      try
      {
         logFile.createNewFile();
      } 
      catch (IOException e)
      {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }
   try
   {
      //BufferedWriter for performance, true to set append to file flag
      BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
      buf.append(text);
      buf.newLine();
      buf.close();
   }
   catch (IOException e)
   {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }
}

Problem

I'm Trying to Write Logs to Custom Log.txt File on Android File using this code of Mine but then this method creates file but contains nothing. Basically I want to read previous contents of the file and then append my data with the existing content. The Code is as follows : ``` public static void write(String str) { InputStream fileInputStream = null; FileOutputStream fileOutpurStream = null; try { fileInputStream = new FileInputStream(file); fileOutpurStream = new FileOutputStream(file); if(file.exists()) { int ch = 0; int current = 0; StringBuffer buffer = new StringBuffer(); while((ch = fileInputStream.read()) != -1) { buffer.append((char) ch); current++; } byte data[]=new byte[(int)file.length()]; fileInputStream.read(data); fileOutpurStream.write(data); fileOutpurStream.write(str.getBytes(),0,str.getBytes().length); fileOutpurStream.flush(); } else { file.createNewFile(); fileOutpurStream.write(str.getBytes(),0,str.getBytes().length); fileOutpurStream.flush(); } } catch(Exception e) { e.printStackTrace(); } finally { try { fileInputStream.close(); fileOutpurStream.flush(); fileOutpurStream.close(); fileOutpurStream = null; fileInputStream = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } ```

Original source

Related problems