0

这是我阅读 .bin 文件的代码。名称:Testfile.bin 位置:资产

在 byteRead(pathtobinfile) 函数中,我想将 bin 文件路径作为字符串传递。

如何获取bin文件路径。请有什么想法!!!

   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;
} 

有什么帮助吗?

4

2 回答 2

0

它是一个非常容易从 Asset 文件夹中读取的 bin 文件。

希望这会对某人有所帮助。

    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();
于 2013-09-16T06:32:09.793 回答
0

实现以下代码,我根据您的要求对其进行了修改。我已经对其进行了测试并且工作得很好。

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();
}

输入

您可以像这样使用此功能。

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

输出

09-16 12:25:34.340: DEBUG/Home(4552): 字节总数: 10
09-16 12:25:34.340: DEBUG/Home(4552): hi Chintan

于 2013-09-16T06:51:25.687 回答