• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps FileInputStream

fastismatt

Lurker
Dec 22, 2009
3
0
I'm trying to read in some large matrices stored in .txt files. My code works fine in my computer (something of which I have a fairly good understanding of how it works), but then not in the Android emulator. This is purely because I don't really have an understanding of the Android file system and I can't seem to access my files correctly. In addition, a lot of other potential solutions I've read have contradicted each other and still don't work for me.

The important part of my code is...

First I use either...

FileInputStream fis = (FileInputStream)con.getResources().openRawResource(R.raw.matrix);

...or...
FileInputStream fis=con.openFileInput("res/raw/matrix.txt");

...then...
BufferedInputStream bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);

So what I'm wondering is are either of those two ways to get a file input stream correct? If not, what is the best way. Also, in which directory do I need to save my text files?

Thanks,
Matt
 
Hi fastismatt,

Your first bit of code looks correct to me.

In one of my apps I have a file called "tunnels.txt" in the project under the "res/raw" folder. And I access the resource with the ID R.raw.tunnels, as shown below:

Code:
public class TempestActivity extends Activity implements OnClickListener {
   . . .
    private void readTunnels() {
        Resources res = this.getResources() ;

        try {
            InputStream is = res.openRawResource(R.raw.tunnels) ;
            TunnelDef.readTunnels(is) ;
            is.close() ;        	
        }
        catch( IOException ioe ) {
        	Log.e("TempestActivity", "readTunnels failed with error: "+ioe) ;
        }
    }
    . . .
}

After that it's just standard Java to read from an InputStream.

If you're reading a file that isn't part of your application, then you'll have to do it differently.


Mark
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones