简体   繁体   中英

Read text and binary from one stream in Java

I'd like to read text and binary from a stream, where the stream could be a file or a URL connection. Both streams have the same format, where there's an ASCII text header followed by a large binary block of data. I'm using DataInputStream to do this. For files, I'm using

DataInputStream dis = new DataInputStream(new FileInputStream(new File("test")));

For URL's, I'm using (where uc is initialized to point to a URL):

DataInputStream dis = new DataInputStream(new BufferedInputStream(uc.getInputStream()));

After setting up the DataInputStream, I follow that with:

dis.readLine()
dis.read(buf);

This works, but I noticed that readLine is depecrated (even though there are posts that refer to using it). Is it OK to keep using it since my text is ASCII? If that's not a good idea, and I go with the JDK recommendation to use BufferedReader, is there a way to access both text and binary? I tried BufferedReader to get the text header, but then I got incorrect binary data when using the underlying stream, probably because some of it was already consumed.

The reason it was deprecated was the failure to properly convert bytes to chars. Since this example is limited to ASCII, there's no problem in using it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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