Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing/Reading Files to/from Android phone's internal memory

Tags:

file

android

I have an utility class named 'MyClass'. The class has two methods to read/write some data into phone's internal memory. I am new to android, Please follow below code.

public class MyClass  {
  public void ConfWrite() {
    try {
      BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new 
                           File(getFilesDir()+File.separator+"MyFile.txt")));
      bufferedWriter.write("lalit poptani");
      bufferedWriter.close();
    } catch (Exception e1) {
        e1.printStackTrace();
    }
  }
}

while executing ConfWrite method, it fails

please provide a better solution to solve this

thanks in advance

like image 342
Riskhan Avatar asked Feb 16 '12 05:02

Riskhan


1 Answers

You can Read/ Write your File in data/data/package_name/files Folder by,

To Write

BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new 
                            File(getFilesDir()+File.separator+"MyFile.txt")));
bufferedWriter.write("lalit poptani");
bufferedWriter.close();

To Read

 BufferedReader bufferedReader = new BufferedReader(new FileReader(new 
                           File(getFilesDir()+File.separator+"MyFile.txt")));
 String read;
 StringBuilder builder = new StringBuilder("");

 while((read = bufferedReader.readLine()) != null){
        builder.append(read);
      }
 Log.d("Output", builder.toString());
 bufferedReader.close();
like image 60
Lalit Poptani Avatar answered Oct 20 '22 18:10

Lalit Poptani