FileInputStream


Last Updated:

  1. fastismatt

    fastismatt New Member This Topic's Starter

    Joined:
    Dec 22, 2009
    Messages:
    3
    Likes Received:
    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
     

    Advertisement
  2. markb

    markb Well-Known Member

    Joined:
    Sep 14, 2009
    Messages:
    148
    Likes Received:
    26
    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 (Text):
    1.  
    2. public class TempestActivity extends Activity implements OnClickListener {
    3.    . . .
    4.     private void readTunnels() {
    5.         Resources res = this.getResources() ;
    6.  
    7.         try {
    8.             InputStream is = res.openRawResource(R.raw.tunnels) ;
    9.             TunnelDef.readTunnels(is) ;
    10.             is.close() ;           
    11.         }
    12.         catch( IOException ioe ) {
    13.             Log.e("TempestActivity", "readTunnels failed with error: "+ioe) ;
    14.         }
    15.     }
    16.     . . .
    17. }
    18.  
    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
     
  3. fastismatt

    fastismatt New Member This Topic's Starter

    Joined:
    Dec 22, 2009
    Messages:
    3
    Likes Received:
    0
    Hey,

    Yeah thanks, I kept messing around with it and realized it worked when I didn't cast InputStream to FileInputStream. Though it didn't show an error when I did cast so why it wasn't working is still lost to me.

    Thanks,
    Matt
     

Share This Page

Loading...