-2

I've been trying to do some research and learn android. I do not understand what the following code does.

public class LogFile extends Activity {
private final static String STORETEXT = "storetext.txt";
private TextView write log;

public void readFileInEditor() {
    try {
        InputStream in = openFileInput(STORETEXT);
        if (in != null) {
            InputStreamReader tmp = new InputStreamReader(in);
            BufferedReader reader = new BufferedReader(tmp);
            String str;
            StringBuilder buf = new StringBuilder();
            while ((str = reader.readLine()) != null) {
                buf.append(str + "\n");
            }
            in.close();
            writelog.setText(buf.toString());
        }
    } catch (java.io.FileNotFoundException e) {
        // that's OK, we probably haven't created it yet
    } catch (Throwable t) {
        Toast.makeText(this, "Exception: " + t.toString(),
                Toast.LENGTH_LONG).show();
    }
}

I don't understand how this method works. Is it reading a file that is referenced with STORETEXT? If it making a file, where is this file saved? And finally, how can I access the "storetext.txt" file so that I may send it using

intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File("/path/to/file"))); 

in an email attachment? Thanks for helping me learn, I've been trying to do some research on this but I am having trouble understanding this concept. Any help is appreciated.

mtorres
  • 197
  • 2
  • 14

3 Answers3

1

This code is reading in a text file "storetext.txt" and then displaying the content of the file in a text view.

The InputStreamReader reads the file and the BufferedReader and the StringBuilder work together to create a long string that has all the contents of the file.

How you access this file to sent with an Intent will depend on where the file is. Is it outside of your app environment, like on the SD card? Or is it in a resource folder like res/raw/storetext.txt?

You'll have to use different methods of getting a reference to your file depending on the situation. Do you know where the file is?

Developer Paul
  • 1,502
  • 2
  • 13
  • 18
1

openFileInput() is used so the file resides in the app specific internal files dir. Use getFilesDir() to find the directory and then add the filename. But.... Other apps have no access to this private directory. So you first have to copy the file to a place where other apps have access.

greenapps
  • 11,154
  • 2
  • 16
  • 19
0

Also, if you are looking to send a file using the intent

intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File("/path/to/file")));

and the file you are trying to send is in the apps private directory, you must use a ContentProvider in order to let other apps(like the native email app) access your file that you wish to send.

Here's a link that was very helpful in helping me figure that out.

http://stephendnicholas.com/archives/974

mtorres
  • 197
  • 2
  • 14