The byte[] that is returned by FileUtils.readFileToByteArray is only the file contents, nothing else.
You should create your own class that is Serializable that includes two fields: a byte[] for the file contents, and a java.io.File that has everything else you need. You then serialize/deserialize your class into byte[], which is transmitted.
The byte[] that is returned by FileUtils.readFileToByteArray is only the file contents, nothing else.
You should create your own class that is Serializable that includes two fields: a byte[] for the file contents, and a java.io.File that has everything else you need. You then serialize/deserialize your class into byte[], which is transmitted.
The file contents and its name are two separate and independent things. While a specific file format could have metadata to store the name in the contents (similar to e.g. ID3 tags for MP3), in a typical file there is no way to know the name from byte [] contents. Also even if, it would be the name from a remote machine which may be invalid on the target platform.
If you want the name you need to transfer it separately.
No. You can take a guess at a mimetype from the content data itself, but the filename is not in there.
The header field that you may be looking for is called Content-Disposition. If you're downloading an attachment, then there may be a file name in that field:
Content-Disposition: attachment;filename=abc.txt
But there's no guarantee that you'll have such a file name available. Also, this may only apply to HTTP and E-Mail content. From your question, it's not clear where your data's origin is...
This is late but if anyone is still looking for an answer.
ByteArrayResource doesn't have any filename by default. See the super class method AbstractResource.getFileName(), it returns null. So until you set the name explicitly while creating ByteArrayResource, it will remain null.
You can achieve this like
ByteArrayResource resource = new ByteArrayResource(bytearray) {
@Override
public String getFilename() {
return "somename";
};
}
Now how to use the actual file name instead of "somename". If you're using Spring, you can define a method in your controller accepting Multipart as an argument.
public ResponseEntity<byte[]> handleFileOperation(Multipart file) {}
Once you get the MultipartFile instance, you can use it the way you want.
You'll probably need to use FileNameAwareByteArrayResource as outlined in Spring-boot MultipartFile issue with ByteArrayResource.
You'll be able to get the filename from it then.
From JDK 7 you can use Files.readAllBytes(Path).
Example:
import java.io.File;
import java.nio.file.Files;
File file;
// ...(file is initialised)...
byte[] fileContent = Files.readAllBytes(file.toPath());
It depends on what best means for you. Productivity wise, don't reinvent the wheel and use Apache Commons. Which is here FileUtils.readFileToByteArray(File input).