3

I have a method that takes in a byte[] that came from Files.readAllBytes() in a different part of the code for either .txt or .docx files. I want to create a new File object from the bytes to later read contents from, without saving that file to disk. Is this possible? Or is there a better way to get the contents from the File bytes?

5
  • 2
    If you don't want interaction with files, dont use File. Pass around the Byte[] or create your own class that wraps the data. Commented Feb 14, 2021 at 19:45
  • How would I get the content out of the file bytes? Commented Feb 14, 2021 at 19:47
  • 2
    The bytes are the content. Commented Feb 14, 2021 at 19:50
  • I get that for text files but what about other file types like .docx and .xlsx? Commented Feb 14, 2021 at 19:59
  • 2
    A file consists only of bytes. The content are the bytes, no matter the file type. Commented Feb 14, 2021 at 20:04

1 Answer 1

6

That's not how it works. a java.io.File object is a light wrapper: Check out the source code - it's got a String field that contains the path and that is all it has aside from some bookkeeping stuff.

It is not possible to represent arbitrary data with a java.io.File object. j.i.File objects represent literal files on disk and are not capable of representing anything else.

Files.readAllBytes gets you the contents from the bytes, that's.. why the method has that name.

The usual solution is that a method in some library that takes a File is overloaded; there will also be a method that takes a byte[], or, if that isn't around, a method that takes an InputStream (you can make an IS from a byte[] easily: new ByteArrayInputStream(byteArr) will do the job).

If the API you are using doesn't contain any such methods, it's a bad API and you should either find something else, or grit your teeth and accept that you're using a bad API, with all the workarounds that this implies, including having to save bytes to disk just to satisfy the asinine API.

But look first; I bet there is a byte[] and/or InputStream variant (or possibly URL or ByteBuffer or ByteStream or a few other more exotic variants).

Sign up to request clarification or add additional context in comments.

1 Comment

I don't know why but I never considered finding a library that can handle bytes instead of File objects so I'll take a look at that. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.