简体   繁体   English

Java InputStream。 有正确有效的方法吗?

[英]Java InputStream . Is there is Correct And Efficient way?

I am working on Bluetooth Application on Android. 我正在研究Android上的蓝牙应用程序。 This inputStream is from connection socket. 此inputStream来自连接套接字。 I want to read bytes upto certain length. 我想读取一定长度的字节。

First way I tried : 我尝试的第一种方式:

byte[] data = new byte[lengthtoread];
for (int i = 0; i < data.length; i++)
    data[i] =(byte) mmInStream.read() ;

I have found that it is been too slow. 我发现它太慢了。

Sencond way: 第二种方式:

   byte[] data = new byte[lengthtoread];
   mmInStream.read(data, 0, lengthtoread);

In this I found that its not reading data completely when length to read is too large 在此我发现,当读取长度太大时,它无法完全读取数据

Anyone please help me out ?? 有人请帮帮我吗??

Using only standard API, the DataInputStream class has a method called readFully that fills a byte array from the stream: 仅使用标准API, DataInputStream类具有一个名为readFully的方法,该方法填充流中的字节数组:

byte[] data = new byte[lengthtoread];
DataInputStream in = new DataInputStream(mmInStream);
in.readFully(data);

Don't forget to close the streams when you are done with them! 完成处理后,不要忘记关闭流!

What, exactly, are you trying to do? 您到底想做什么?

If it's to read all the bytes from a file, then do this: 如果要从文件读取所有字节,请执行以下操作:

Files.readAllBytes(Paths.get("filename.txt")); Files.readAllBytes(Paths.get( “FILENAME.TXT”));

http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllBytes%28java.nio.file.Path%29 http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllBytes%28java.nio.file.Path%29

Yes: use Jakarta Commons IOUtils . 是的:使用Jakarta Commons IOUtils This class contains fully-debugged utility methods for reading and writing streams. 此类包含用于调试和读取流的完全调试的实用程序方法。

If you want to read the entire stream, use IOUtils.toByteArray() . 如果要读取整个流,请使用IOUtils.toByteArray() However, be aware that you might run out of memory when doing this. 但是,请注意,这样做可能会耗尽内存。 Usually it's better to process a piece of a stream at a time. 通常最好一次处理一条流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM