Use the FileUtils#readFileToByteArray(File) from Apache Commons IO, and then create the ByteArrayInputStream using the ByteArrayInputStream(byte[]) constructor.

public static ByteArrayInputStream retrieveByteArrayInputStream(File file) {
    return new ByteArrayInputStream(FileUtils.readFileToByteArray(file));
}
Answer from npe on Stack Overflow
🌐
Coderanch
coderanch.com › t › 277921 › java › ByteArrayInputstream-file
ByteArrayInputstream to a file (I/O and Streams forum at Coderanch)
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums · this forum made possible by our volunteer staff, including ... ... hi , i find out way ByteArrayInputStream byteArrayInputStream = sysObj.getContent(); String outStr=byteArrayInputStream.toString(); File newFile=new File("somefilname"); FileOutputStream fos = new FileOutputStream(newFile); int data; while((data=byteArrayInputStream.read())!=-1) { char ch = (char)data; fos.write(ch); } fos.flush(); fos.close(); thanks
Discussions

arrays - byte[] to file in Java - Stack Overflow
With Java: I have a byte[] that represents a file. How do I write this to a file (ie. C:\myfile.pdf) I know it's done with InputStream, but I can't seem to work it out. More on stackoverflow.com
🌐 stackoverflow.com
Convert InputStream to byte array in Java - Stack Overflow
Java documentation "Note that this method is intended for simple cases where it is convenient to read all bytes into a byte array. It is not intended for reading input streams with large amounts of data." and in fact it was limited to 8192 from my test (undocumented) Use it for test, but not in production. 2021-12-17T14:52:39.503Z+00:00 ... @pdem there is no such limit. I just verified it by reading a 2GiB file ... More on stackoverflow.com
🌐 stackoverflow.com
java - Byte[] to InputStream or OutputStream - Stack Overflow
I have a blob column in my database table, for which I have to use byte[] in my Java program as a mapping and to use this data I have to convert it to InputStream or OutputStream. But I don't know ... More on stackoverflow.com
🌐 stackoverflow.com
"FileInputStream obtains bytes from a file" - What does this mean exactly?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnjava
8
6
August 23, 2023
🌐
Tutorialspoint
tutorialspoint.com › java › java_bytearrayinputstream.htm
Java - ByteArrayInputStream
Java Vs. C++ ... The ByteArrayInputStream class allows a buffer in the memory to be used as an InputStream. The input source is a byte array. ByteArrayInputStream class provides the following constructors.
🌐
How to do in Java
howtodoinjava.com › home › i/o › writing byte[] to a file in java
Writing Byte[] to a File in Java
April 18, 2022 - Do not forget to close the output ... FileOutputStream(file)) { os.write(bytes); } The FileUtils class has method writeByteArrayToFile() that writes the byte array data into the specified file....
🌐
Medium
medium.com › @lavishj77 › java-i-o-byte-stream-implementation-6acf5a9ec848
Java I/O Byte Stream Implementation | by Lavish Jain | Medium
April 16, 2022 - File I/O, either reading it or writing uses expensive and limited operating system resources, and so when you’re done, invoking close() will free up those resources. Used to read and write from and to a byte array. String text = "Awesome Java"; InputStream bis = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)); //read() method implementation is same as that of FileInputStream.ByteArrayOutputStream bos = new ByteArrayOutputStream(); //write() method implementation same as that of FileOutputputStream.
Find elsewhere
🌐
Baeldung
baeldung.com › home › java › java io › writing byte[] to a file in java
Writing byte[] to a File in Java | Baeldung
May 13, 2026 - We’ll open an output stream to our destination file, and then we can simply pass our byte[] dataForWriting to the write method. Note that we’re using a try-with-resources block here to ensure that we close the OutputStream in case an IOException is thrown. The Java NIO package was introduced in Java 1.4, and the file system API for NIO was introduced as an extension in Java 7.
🌐
Oracle
docs.oracle.com › en › java › javase › 21 › docs › api › java.base › java › io › ByteArrayInputStream.html
ByteArrayInputStream (Java SE 21 & JDK 21)
July 15, 2025 - Reads up to len bytes of data into an array of bytes from this input stream. If pos equals count, then -1 is returned to indicate end of file. Otherwise, the number k of bytes read is equal to the smaller of len and count-pos. If k is positive, then bytes buf[pos] through buf[pos+k-1] are copied ...
🌐
Baeldung
baeldung.com › home › java › java io › java inputstream to byte array and bytebuffer
Java InputStream to Byte Array and ByteBuffer | Baeldung
January 8, 2024 - In this quick tutorial, we’re ... an InputStream to a byte[] and ByteBuffer – first using plain Java, then using Guava and Commons IO. This article is part of the “Java – Back to Basic” series here on Baeldung. Discover Spring's StreamUtils class. ... We learn how to serialize and deserialize objects in Java. ... Quick and practical examples focused on converting String objects to different data types in Java. ... Let’s look at obtaining a byte array from simple ...
🌐
Programiz
programiz.com › java-programming › bytearrayinputstream
Java ByteArrayInputStream (With Examples)
In this tutorial, we will learn about Java ByteArrayInputStream and its methods with the help of examples to read an array of input data.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › io › ByteArrayInputStream.html
ByteArrayInputStream (Java Platform SE 8 )
April 21, 2026 - Reads up to len bytes of data into an array of bytes from this input stream. If pos equals count, then -1 is returned to indicate end of file. Otherwise, the number k of bytes read is equal to the smaller of len and count-pos. If k is positive, then bytes buf[pos] through buf[pos+k-1] are copied ...
🌐
Jenkov
jenkov.com › tutorials › java-io › bytearrayinputstream.html
Java ByteArrayInputStream
November 15, 2019 - The Java ByteArrayInputStream can be handy if your data is stored in an array, but you have a component that can only process it as an InputStream. The ByteArrayInputStream can thus wrap the byte array, and turn it into a stream.
Top answer
1 of 8
213

You create and use byte array I/O streams as follows:

byte[] source = ...;
ByteArrayInputStream bis = new ByteArrayInputStream(source);
// read bytes from bis ...

ByteArrayOutputStream bos = new ByteArrayOutputStream();
// write bytes to bos ...
byte[] sink = bos.toByteArray();

Assuming that you are using a JDBC driver that implements the standard JDBC Blob interface (not all do), you can also connect a InputStream or OutputStream to a blob using the getBinaryStream and setBinaryStream methods1, and you can also get and set the bytes directly.

(In general, you should take appropriate steps to handle any exceptions, and close streams. However, closing bis and bos in the example above is unnecessary, since they aren't associated with any external resources; e.g. file descriptors, sockets, database connections.)

1 - The setBinaryStream method is really a getter. Go figure.

2 of 8
14

I'm assuming you mean that 'use' means read, but what i'll explain for the read case can be basically reversed for the write case.

so you end up with a byte[]. this could represent any kind of data which may need special types of conversions (character, encrypted, etc). let's pretend you want to write this data as is to a file.

firstly you could create a ByteArrayInputStream which is basically a mechanism to supply the bytes to something in sequence.

then you could create a FileOutputStream for the file you want to create. there are many types of InputStreams and OutputStreams for different data sources and destinations.

lastly you would write the InputStream to the OutputStream. in this case, the array of bytes would be sent in sequence to the FileOutputStream for writing. For this i recommend using IOUtils

byte[] bytes = ...;//
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
FileOutputStream out = new FileOutputStream(new File(...));
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);

and in reverse

FileInputStream in = new FileInputStream(new File(...));
ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
byte[] bytes = out.toByteArray();

if you use the above code snippets you'll need to handle exceptions and i recommend you do the 'closes' in a finally block.

🌐
Javatpoint
javatpoint.com › java-bytearrayinputstream-class
Java ByteArrayInputStream Class - javatpoint
Java ByteArrayInputStream Class for beginners and professionals with examples on Java IO or Input Output in Java with input stream, output stream, reader and writer class. The java.io package provides api to reading and writing data.
🌐
Programiz
programiz.com › java-programming › bytearrayoutputstream
Java ByteArrayOutputStream (With Examples)
Here, the size specifies the length of the array. The ByteArrayOutputStream class provides the implementation of the different methods present in the OutputStream class. write(int byte) - writes the specified byte to the output stream
🌐
Mkyong
mkyong.com › home › java › java – how to convert file to byte[]
Java - How to convert File to byte[] - Mkyong.com
September 17, 2020 - Java – How to save byte arrays to a file · Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities. 9 Comments · Most Voted · Newest Oldest · Inline Feedbacks · View all comments · dazz · 8 years ago · try { byte[] bFile = Files.readAllBytes(Paths.get(“/home/input_test.png”)); // save byte[] into a file Path path = Paths.get(“/home/output_test.png”); // The CREATE option is necessary.
🌐
Reddit
reddit.com › r/learnjava › "fileinputstream obtains bytes from a file" - what does this mean exactly?
r/learnjava on Reddit: "FileInputStream obtains bytes from a file" - What does this mean exactly?
August 23, 2023 -

I'm learning about java.io package and one thing I don't understand. FileInputStream class is recommended for obtaining "input bytes from a file in a file system". What does this mean exactly? If I get a text file using this class, or an images, how do those bytes "look" like? What if I obtain a pdf file? Do I get bytes that describe its content? What about a Word file? Do those files contain every text formatiing done to the text?

Top answer
1 of 5
4
To understand what that means, you'll need more familiarity with the fundamentals of how files of all types are saved to disk. It's a very long explanation - here is an abridged version: Every file on your computer is saved to a long-term memory store that persists information even if power is removed. Call this the hard disk, or just disk for short (not disc). Every running program on your computer exists in a memory space that is faster than the hard disk as a work area - call it RAM. Files are typically "loaded" into this area if they need to be manipulated or immediately used. When you play a video game and it is "loads" a level - this is what's happening. Every file, regardless of if its a bitmap image, Word doc, text doc, or binary file - is represented on disk as a series of 1s and 0s but mostly commonly can be viewed and interpreted as base16 hex characters (same info, more compact to read). Download a hex editor, open a file. You'll see the byte representation of the file. It'll look like nonsense. That's what's being loaded into your Java program's workable memory area when you "obtain bytes". Different file formats will have very unique and unintuitive ways to save data, a Word doc has a huge amount of extra overhead to save formatting, and it's encoded and dispersed throughout the file in such a clever way - the byte representation of it may not make any sense even though the file manifests as human readable text once you open it. Open different types of files to see what you can learn from that. So to answer your question, what does "obtains bytes mean exactly?" It means the Java program is loading the bytes of the file currently on disk, and loading all of the bytes of that file into a working memory area (RAM) where the Java program can manipulate it quickly and safely (that is: without altering the version on disk) by allowing you to assign it to a variable within the context of your program.
2 of 5
2
FileInputStream is just another layer on top of a mountain of abstractions. The abstraction of drivers that hide the physical nature of how data is stored .e. g. SSD or HDD. The abstractions of the filesystem that combines bits of data into a hierarchy of files and folders, the abstractions of the operating system that hides the filesystem .e.g FAT32 or NTFS, and on top of all the abstractions of Java that hides the operating system and let you do I/O operations without worrying about what operating system they're gonna run on. To be honest, it's gonna be really tough to understand this by just looking at the highest layer. You're gonna have to dig a little deeper to get the whole picture. From a personal experience, taking a course on operating systems or reading a book about the subject or both will be really helpful.