thpitsch
thpitsch

Reputation: 2036

FileInputStream for a raw file

I have a raw file in res/raw named "pack.dat".

I can open an InputStream with the following code:

    InputStream fis = null;
    try {
        fis = context.getResources().openRawResource(R.raw.pack);
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));
        String nextLine;
        int i = 0, j = 0;
        while ((nextLine = br.readLine()) != null) {
            if (j == 5) {
                j = 0;
                i++;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

This is working, I can read from that file.

But unfortunately I need a FileInputStream. When I do this:

    FileInputStream fs = null;
    Uri url = Uri.parse("android.resource://" + 
                     context.getPackageName() + "/" + R.raw.pack);
    File file = new File(url.toString());
    try {
        fs = new FileInputStream(file);
        fs.getChannel().position(0);
        fs.read(bDatensatz, 0, indexlaenge);
    } catch (Exception e) {
        e.printStackTrace();
    }

I get a "file not found" at

fs = new FileInputStream(file);

context.getResources().openRawResource(R.raw.pack) in the first example returns an InputStream.

What can I use to get a FileInputStream instead?

Upvotes: 0

Views: 3702

Answers (2)

ishwor kafley
ishwor kafley

Reputation: 938

copied from another thread! may be this should help you

FileInputStream fis;
fis = openFileInput("test.txt");
StringBuffer fileContent = new StringBuffer("");

byte[] buffer = new byte[1024];
int n  = 0;

while ((n = fis.read(buffer)) != -1) 
{ 
  fileContent.append(new String(buffer, 0, n)); 
} 

Upvotes: 2

CommonsWare
CommonsWare

Reputation: 1007099

But unfortunately I need a FileInputStream

Why?

I get a "file not found" at fs = new FileInputStream(file);

That is because you are trying to open something that is not a file.

What can I use to get a FileInputStream instead?

You would need to copy the resource to a local file (e.g., using openFileOutput() and Java I/O). Then, you can open the local file (e.g., using openFileInput()) and get a FileInputStream.

Or, just use the InputStream, fixing whatever code that you are using that is expecting a FileInputStream.

Upvotes: 1

Related Questions