Monday, March 31, 2014

Write/Read data into file in Android

Function to write text to file.

 private void writeToFile(String text) throws IOException {
   
  File file= new File("sdcard/android.file"); //location to write
  if (!file.exists())
  {
     try
     {
        file.createNewFile();
     }
     catch (IOException e)
     {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
  }
  try
  {
     //appending data to file
     BufferedWriter writeBuffer = new BufferedWriter(new FileWriter(file, true));
      writeBuffer .append(text);
      writeBuffer .newLine();
      writeBuffer .close();
  }
  catch (IOException e)
  {
     // TODO Auto-generated catch block
     e.printStackTrace();
  }
}

Function to read the text from file 

private String readFromFile() {
        File file= new File("sdcard/android.file"); //location to read
        StringBuilder text = new StringBuilder();
        try {
            BufferedReader readBuffer = new BufferedReader(new FileReader(file));
            String line;
            while ((line = readBuffer.readLine()) != null) {
                text.append(line);
                text.append('\n');
            }
        }
        catch (IOException e) {
            //error handling.
        }
        return text.toString();
    }