Java 6 read file into byte array
Learn more. Elegant way to read file into byte[] array in Java [duplicate] Ask Question. Asked 10 years, 8 months ago. Active 3 years, 7 months ago. Viewed k times. Improve this question. Community Bot 1 1 1 silver badge. Arseniy Arseniy 1, 1 1 gold badge 19 19 silver badges 35 35 bronze badges. Add a comment. Active Oldest Votes. A long time ago: Call any of these byte[] org. For instance: byte[] java. Improve this answer. Demetrios Christopher 2 2 silver badges 9 9 bronze badges. Lukas Eder Lukas Eder k gold badges silver badges bronze badges.
How to do the same in Android? Any ideas..? There are also other answers here that show how to do this using the old java. InputStream API Show 4 more comments. This will also work: import java.
Paul Paul 5 5 silver badges 2 2 bronze badges. To stream a file, you need to step away from Files. It's a nice utility for small files, but as you noticed not so much for large files. In Java, you can use a FileInputStream to read a file byte by byte or chunk by chunk. Lets say we want to write back our processed bytes. First we open the files:. We need the FileOutputStream to write back our results - we don't want to just drop our precious processed data, right?
Next we need a buffer which holds a chunk of bytes:. How many bytes is up to you, I kinda like chunks of bytes. Then we need to actually read some bytes. It will return the total bytes read. Then we process the bytes:. It takes in a byte-array, the number of bytes it should process and returns the result as byte-array.
We have to execute this in a loop until there are no bytes left in the file, so lets write a loop for it:. And thats it. We processed the file in byte chunks and wrote the result back to a file. It's up to you what to do with the result, you could also send it over TCP or even drop it if it's not needed, or even read from TCP instead of a file, the basic logic is the same.
This still needs some proper error-handling to work around missing files or wrong permissions but that's up to you to implement that. Stack Overflow for Teams — Collaborate and share knowledge with a private group. Create a free Team What is Teams? Collectives on Stack Overflow. Learn more. Java Reading large files into byte array chunk by chunk Ask Question.
And what if you want to generate number from 0 to like R,G,B for making color.. How looks code for that? Read file in byte array using FileInputStream. This example shows how to read a file in byte array using Java FileInputStream. This method should only be used when the file size is less. Output would be. File content :. This file is for demonstration of how to read file in byte array. Want to learn quickly? Try one of the many quizzes. More than Java questions with detailed answers.
Yes, I want to learn Java quickly. You may also like.
0コメント