Question

This is my code for Reading .bin file. name:Testfile.bin location : Assets

In the byteRead(pathtobinfile) function I want to pass bin file path as a String.

how to get the bin file path. Any idea please!!!

   public byte[] byteRead(String aInputFileName)
{

        File file = new File(aInputFileName);
        byte[] result = new byte[(int)file.length()];
        try {
          InputStream input = null;
          try {
            int totalBytesRead = 0;
            input = new BufferedInputStream(new FileInputStream(file));
            while(totalBytesRead < result.length){
              int bytesRemaining = result.length - totalBytesRead;
              //input.read() returns -1, 0, or more :
              int bytesRead = input.read(result, totalBytesRead, bytesRemaining); 
              if (bytesRead > 0){
                totalBytesRead = totalBytesRead + bytesRead;
              }
            }

          }
          finally {
            //log("Closing input stream.");
            input.close();
          }
        }
        catch (FileNotFoundException ex) {
          ex.printStackTrace();
        }
        catch (IOException ex) {

            ex.printStackTrace();
        }

        Log.d("File Length",  "Total No of bytes"+ result.length);

        return result;
} 

Any help?

Was it helpful?

Solution

Implement following code, which I modified as per your requirement. I have tested it and working very well.

public byte[] byteRead(String aInputFileName) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        InputStream input = getResources().getAssets().open(aInputFileName);
        try {
            byte[] buffer = new byte[1024];
            int read;
            while ((read = input.read(buffer)) != -1) {
                baos.write(buffer, 0, read);
            }

        } finally {
            input.close();
        }
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    Log.d("Home", "Total No of bytes : " + baos.size());

    return baos.toByteArray();
}

Input

You can use this function like this.

byte[] b = byteRead("myfile.txt");
String str = new String(b);
Log.d("Home", str);

Output

09-16 12:25:34.340: DEBUG/Home(4552): Total No of bytes : 10
09-16 12:25:34.340: DEBUG/Home(4552): hi Chintan

OTHER TIPS

Its a very easy to read bin file from Asset folder.

Hope this will help someone.

    InputStream input = context.getAssets().open("Testfile.bin");
    // myData.txt can't be more than 2 gigs.
    int size = input.available();
    byte[] buffer = new byte[size];
    input.read(buffer);
    input.close();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top