Read file from sd - what's the best way?

Put your problem here if it does not fit any of the other categories.

Read file from sd - what's the best way?

Postby Marbert » Sat Feb 04, 2012 7:41 pm

Hello!

If I press a button in my app, I can save a file to datata/com.josh.test/files/text.txt .

Code: Select all
String sFilename = "text.txt";
            String sWriteFile = sEncodedText;

            try
            {
               java.io.FileOutputStream fos = openFileOutput(sFilename, Context.MODE_WORLD_READABLE);
               fos.write(sWriteFile.getBytes());
               fos.close();
catch
{
...


Ok, this works without any problems. But now I want to read in a file from the public space of the sdcard (the part you can access to without root,...).

But how to do this the best way? So I want to read in the content of the file and write it to another text view.

Thanks,
Josh
Marbert
Developer
Developer
 
Posts: 30
Joined: Sat Feb 04, 2012 7:31 pm

Top

Re: Read file from sd - what's the best way?

Postby jonbonazza » Sat Feb 04, 2012 8:20 pm

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. public String readFromFile(String filename)
  2. {
  3.        BufferedReader br = new BufferedReader(new FileReader(filename));
  4.  
  5.        String tmp = null;
  6.        String result = "";
  7.        while((tmp = br.readLine()) != null)
  8.               result += tmp;
  9.  
  10.         br.close();
  11.  
  12.         return result;
  13. }
  14.  
Parsed in 0.032 seconds, using GeSHi 1.0.8.4
jonbonazza
Master Developer
Master Developer
 
Posts: 665
Joined: Thu Jul 15, 2010 2:58 pm
Location: WV USA

Re: Read file from sd - what's the best way?

Postby Marbert » Sat Feb 04, 2012 9:08 pm

Ok, thanks. But what does the plus at 'result+=' mean?

And what is filename? It's a String, but how does it have to look like? Just the filename (text.txt) or the path (/sdcard/text.txt)?

I've started learning Java 1.5 years ago, but started Android only a month ago and so I still have some problems with reading in the file. I hope you'll excuse me. ;)
Marbert
Developer
Developer
 
Posts: 30
Joined: Sat Feb 04, 2012 7:31 pm

Re: Read file from sd - what's the best way?

Postby jonbonazza » Sun Feb 05, 2012 2:40 am

result += tmp; is shorthand for result = result + tmp;

As for filename, it should be the whole path. Sry, I should have elaborated.
jonbonazza
Master Developer
Master Developer
 
Posts: 665
Joined: Thu Jul 15, 2010 2:58 pm
Location: WV USA

Re: Read file from sd - what's the best way?

Postby Phyll » Sun Feb 05, 2012 6:50 am

Hi Marbert,

The sdcard is not always /sdcard sometimes it is somewhere else, use this:

File extStore = Environment.getExternalStorageDirectory();

to find where it is. Here is a class you can use to read and write text files anywhere it is allowed. Study it and use what you want from it.

Code: Select all
package com.bandpsoftware.scrambler;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
import android.util.Log;

public class TextFile {

   public static boolean PRIVATE_MODE = false;
   public static boolean PUBLIC_MODE = true;

    private String pathStr;
    private String fileStr;
    private boolean mode;
    private Context con;

   public TextFile(Context context, String path, String filename) {
       pathStr = path;
       fileStr = filename;
       mode = PRIVATE_MODE;
       con = context;
       }//constructor

   public boolean CheckPath() {
       try {
             File file = new File(pathStr);
              if (file.exists()==false) {
                if (file.mkdir()==false) return false;
                  }//if no file yet
            }//get main folder
            catch (Exception e) {
                Log.e("CHECKPATH","Error "+e.getMessage());
               return false;
               }//catch
        return true;
       }//checkpath

   public boolean writeTextFile(String text) {
       byte[] buffer;
       FileOutputStream fos;
       try {
            String fs = MakeFileName();
            if (mode==PUBLIC_MODE) fos = new FileOutputStream(fs);
                else fos = con.openFileOutput(fs, Context.MODE_PRIVATE);
           buffer = text.getBytes("UTF-8");
           fos.write(buffer, 0, buffer.length);
           fos.close();
           return true;
           }//try
           catch (IOException e) {
               Log.d("WRITEFILE","Error "+e.getMessage());
               return false;
               }//catched
       }//writetextfile

    public String readTextFile() {
        int b;
        String buf="";
        byte[] buffer = new byte[1000];
        FileInputStream fis;
        try {
           String fs = MakeFileName();
            if (mode==PUBLIC_MODE) fis = new FileInputStream(fs);
                else fis = con.openFileInput(fs);
            do {
                b=fis.read(buffer);
                if (b>-1) buf=buf+new String(buffer,0,b,"UTF-8");
                }//do
            while (b!=-1);
            fis.close();
            return buf;
            }//try
            catch (IOException e) {
                Log.d("READFILE","Error "+e.getMessage());
                buf = "";
                }//catched it
        return buf;
        }//readtextfile

   private String MakeFileName() {
        String s = "";
        mode = PRIVATE_MODE;
        if (pathStr.length()!=0) {
            File file = new File(pathStr);
            s = file.toString()+"/";
            mode = PUBLIC_MODE;
           }//get path name
       s = s+fileStr;
       return s;
       }//makefilename

}//class


Use it like this for example to check for and create if necessary the existence of a particular folder:

Code: Select all

public static final String DEFAULT_PATH = "/SCRAM";

        //Find our folder
        File extStore = Environment.getExternalStorageDirectory();
        String ss = extStore.getPath()+DEFAULT_PATH;
        TextFile tf = new TextFile(this,ss,MAIN_FILE);
        if (!tf.CheckPath()) Log.e("CHECKPATH","Error "+ss);
            else dataPath = ss;


Then write or read files something like this:

Code: Select all
      TextFile tf = new TextFile(Scrambler.this,dataPath,MAIN_FILE);
      String ss = tf.readTextFile();


Hope this helps.

Phyll
Phyll
Master Developer
Master Developer
 
Posts: 648
Joined: Fri Oct 14, 2011 11:19 am

Re: Read file from sd - what's the best way?

Postby Marbert » Sun Feb 05, 2012 5:53 pm

Thanks a lot, this will help me for sure! :)

And what if I want to send the file which is located in /datadata/....?
I want a popup windows where you can choose which other app you want to use for sharing (GMail, Mail, Google+,...)?

I don't know if it's the right forum, but I think I'll ask the question though. ;) I've been using Linux Mint (based on Ubuntu) for 3 months now on my other PC. On my notebook (which I use for coding) is only Win7. Is there a possibility to replace the ugly Eclipse-font in WIndows with the more beautiful font from Ubuntu?
Marbert
Developer
Developer
 
Posts: 30
Joined: Sat Feb 04, 2012 7:31 pm

Top

Re: Read file from sd - what's the best way?

Postby jonbonazza » Sun Feb 05, 2012 6:59 pm

I am assuming you meant the "/data/data" directory. If that's the case, you simply need to provide that directory as a String literal. Unlike external storage, the internal directories will be the same on every device as it is an important part of the Operating System itself. With that said, keep in mind that, without root permissions, you cannot write to internal storage--only read from it, as by default, it is read only and no write permissions are enabled. This cannot be changed without root access.
jonbonazza
Master Developer
Master Developer
 
Posts: 665
Joined: Thu Jul 15, 2010 2:58 pm
Location: WV USA

Re: Read file from sd - what's the best way?

Postby Phyll » Sun Feb 05, 2012 10:19 pm

Hi marbert,

With the class you have there, leaving the path an empty string will automatically read or write a private file which exists in the /data/data/package.name folder. This folder and the folders below it are accessible to only your program. This class can read and write there either way, with or without a path, but it automatically goes to that folder when you leave the path blank. Files there are known as private files. Files elsewhere are known as public files.

But, to read or write a subdirectory there you will have to spell it out:

path = "/data/data/package.name/subdir"

and then provide the filename of the file you want.

Hope this is helpful.

Phyll
Phyll
Master Developer
Master Developer
 
Posts: 648
Joined: Fri Oct 14, 2011 11:19 am

Re: Read file from sd - what's the best way?

Postby Marbert » Mon Feb 06, 2012 2:12 pm

@jonbonazza: hm, I can access the saved file under /atata/com.josh.test/files/text.txt , but it also works with your suggestion (/data/data/com.josh.test/files/text.txt. And yes, the internal paths must be the same (like Windows with the system-foder. :)


@Phyll: ok thanks, I didn't know the exact procedure. :)


@all: I'll try to finish the read-in-process, thanks for all your help! I hope I may ask you if there are any further questions?

And anybody knows, if I can use the Ubuntu-Eclipse-font for WIndows too (is there any way)?
Marbert
Developer
Developer
 
Posts: 30
Joined: Sat Feb 04, 2012 7:31 pm

Re: Read file from sd - what's the best way?

Postby Phyll » Mon Feb 06, 2012 3:32 pm

Hi Marbert,

Don't know too much about the fonts on Ubuntu and Windows but here's something that might help. Looks possible anyway: http://techie-buzz.com/ubuntu/ubuntu-fo ... ndows.html

Phyll
Phyll
Master Developer
Master Developer
 
Posts: 648
Joined: Fri Oct 14, 2011 11:19 am

Re: Read file from sd - what's the best way?

Postby Marbert » Mon Feb 06, 2012 4:04 pm

Thanks. But it doesn't look good with Windows, so I'll have to use the standard Windows-font.
Marbert
Developer
Developer
 
Posts: 30
Joined: Sat Feb 04, 2012 7:31 pm

Re: Read file from sd - what's the best way?

Postby Marbert » Mon Feb 06, 2012 4:40 pm

I startet a new project for testing the read-in-process. But I have a little mistake I cannot find. :cry:

The layout has only a button and a TextView. I've created a file /sdcard/readmein.txt . If I press the button the text should be read in.


Code: Select all
package com.josh.test2;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Android_ReadFileActivity extends Activity
{
   Button btnReadIn;
   TextView tvResult;
   String sResult= "";
   
   public String readFromFile(String filename) throws IOException
     {
        BufferedReader brRead = new BufferedReader(new FileReader(filename));
        filename ="/sdcard/readmein.txt";
        String sTmp;
       
        try
        {
           while((sTmp = brRead.readLine()) != null)
           {
            sResult = sResult + sTmp;
           }
           return sResult;
        }
       
        catch (IOException e)
        {
                 e.printStackTrace();
        }

        brRead.close();
        return sResult;
     }
   
   
   public void onCreate(Bundle savedInstanceState)
   {
      super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       
       btnReadIn = (Button) findViewById(R.id.btnReadIn);
       tvResult = (TextView) findViewById(R.id.tvResult);
       
       
       btnReadIn.setOnClickListener (new View.OnClickListener()
       {
          public void onClick (View V)
          {
             try
             {
                readFromFile(sResult);
                tvResult.setText(sResult.toString());
             }
             
             catch (IOException e)
             {
                e.printStackTrace();
             }
          }
       });
   }
}

Marbert
Developer
Developer
 
Posts: 30
Joined: Sat Feb 04, 2012 7:31 pm

Re: Read file from sd - what's the best way?

Postby jonbonazza » Mon Feb 06, 2012 7:08 pm

Your issue is that inside your readFromFileMethod, you take as a parameter a string, create the Buffered reader from that string, then create a new string with the filename. This is wasteful design and wouldn't necessarily cause an issue other than poorly written code... BUT when you actually CALL that method inside your onClick() method, you are passing it an empty string (sResult).
jonbonazza
Master Developer
Master Developer
 
Posts: 665
Joined: Thu Jul 15, 2010 2:58 pm
Location: WV USA

Re: Read file from sd - what's the best way?

Postby Marbert » Mon Feb 06, 2012 7:20 pm

Ok, what would be a good coding style?

And what do I have to pass to the onClick()-method? I thought that sResult is returned so I have to give it to the onClick-Method...
Marbert
Developer
Developer
 
Posts: 30
Joined: Sat Feb 04, 2012 7:31 pm

Re: Read file from sd - what's the best way?

Postby jonbonazza » Mon Feb 06, 2012 9:53 pm

In java, strings are not mutable. your method returns a string. the string you need to GIVE it is the string containing the filename.

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. public String readFromFile(String filename) throws IOException
  2.      {
  3.         BufferedReader brRead = new BufferedReader(new FileReader(filename));
  4.         String sTmp;
  5.         String result = "";
  6.         try
  7.         {
  8.            while((sTmp = brRead.readLine()) != null)
  9.            {
  10.             sResult = sResult + sTmp;
  11.            }
  12.         }
  13.        
  14.         catch (IOException e)
  15.         {
  16.                  e.printStackTrace();
  17.         }
  18.  
  19.         brRead.close();
  20.         return sResult;
  21.      }
  22.  
Parsed in 0.033 seconds, using GeSHi 1.0.8.4


then in your onClick method:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. public void onClick (View V)
  2.           {
  3.              try
  4.              {
  5.                 String returnedString = readFromFile("/sdcard/readmein.txt");
  6.                 tvResult.setText(returnedString);
  7.              }
  8.              
  9.              catch (IOException e)
  10.              {
  11.                 e.printStackTrace();
  12.              }
  13.           }
  14.  
Parsed in 0.035 seconds, using GeSHi 1.0.8.4
jonbonazza
Master Developer
Master Developer
 
Posts: 665
Joined: Thu Jul 15, 2010 2:58 pm
Location: WV USA

Top
Next

Return to Other Coding-Problems

Who is online

Users browsing this forum: No registered users and 16 guests