这是我的阅读.bin文件的代码。 name: Testfile.bin location:资产
在byteRead(pathtobinfile)函数中,我希望将bin文件路径作为String传递。
如何获取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;
}
有任何帮助吗?
答案 0 :(得分: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();
答案 1 :(得分: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):嗨Chintan