Avatar ·

How to convert a file to a byte array (byte[]) in Java?

Hello everyone! I'm a beginner in Java and I've encountered a problem: I need to read an entire file and get its contents as a byte array (byte[]). The specific task is to load an image from disk and send it via an HTTP request. I've tried several approaches, but they all seem cumbersome or lead to errors. For example, I tried using FileInputStream:
File file = new File("image.jpg");
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();
But this code sometimes doesn't read the entire file, especially if it's large. I've also heard about Apache Commons IO, but I don't want to add external libraries for such a simple task. Please advise how to correctly and reliably read a file into a byte array.