How to convert the Video file to byte array? - java

I need to convert a video file to byte array and then send the byte array to a server, but when I upload the byte array the server did not receive it in the correct format. I convert the file like below:-
buffer=new byte[1024];
os=new ByteArrayOutputStream();
FileInputStream fis=new FileInputStream(file);
int read;
while ((read=fis.read(buffer))!=-1){
os.write(buffer,0,read);
}
fis.close();
os.close();

Following are the ways to convert the file into byte[]
First
File file = new File(path);
int size = (int) file.length();
byte[] bytes = new byte[size];
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(bytes, 0, bytes.length);
buf.close();
Second
byte bytes[] = new byte[(int) file.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
DataInputStream dis = new DataInputStream(bis);
dis.readFully(bytes);
Third
byte bytes[] = FileUtils.readFileToByteArray(photoFile)
The only drawback is to add this dependency in your build.gradle app :
implementation 'commons-io:commons-io:2.5'

File file = new File("filepath");
//init array with file length
byte[] bytesArray = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bytesArray); //read file into bytes[]
fis.close();
return bytesArray;
Try this! hopefully it will work.

Related

only first few hundred samples are read from input stream into byte array(the rest are zeros)

i'm trying to convert audio(mp3/wav etc.) to byte array. i did it using inputStream to byte array conversion.
the problem is that after few hundred samples i recieve only zeroes.
at first i thought the problem was with the file so i tried debugging with another file and had the same problem.
I thought the problem was with the code so i tried using IOUtils and got the exact same resualts.
can anyone tell me what i'm doing wrong?
the code i used:
File file = new File(path);
final InputStream inputStream = new FileInputStream(file);
byte[] byteSamples = inputStreamToByteArray(inputStream);
public byte[] inputStreamToByteArray(InputStream inStream) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = inStream.read(buffer)) > 0) {
baos.write(buffer, 0, bytesRead);
}
return baos.toByteArray();
}
the alternate version using IOUtils:
byte[] byteSamples = IOUtils.toByteArray(inputStream);
update : i tried doing it using BufferedInputStream, still the exact same results.
byte[] byteSamples = new byte[(int)file.length()];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(byteSamples, 0, byteSamples.length);
buf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();}
You need to close the streams when done.

Zipping files with ZipOutputStream gives inconsistent results

I want to zip a text file using the java.util.ZipOutputStream class. I found two examples on the internet explaining on how to do that. This led me to the two possible implementations shown below. While both methods produce 'healthy zip files', my problem is that on every run the binary content of the file is slightly different (around the 10th byte). Does someone know if
This is intended behaviour
There is a way to always produce exactly the same result
Here is my current code:
public byte[] getZipByteArray(String fileName) throws IOException
{
byte[] result = new byte[0];
byte[] buffer = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
ZipEntry ze = new ZipEntry(fileName);
zos.putNextEntry(ze);
InputStream inputStream = ZipCompression.class.getResourceAsStream(fileName);
int len;
while ((len = inputStream.read(buffer)) > 0)
{
zos.write(buffer, 0, len);
}
zos.closeEntry();
zos.close();
result = baos.toByteArray();
return result;
}
public byte[] ZipByteArrayBuffered(String fileName) throws IOException
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(byteArrayOutputStream);
ZipOutputStream zipOutputStream = new ZipOutputStream(bufferedOutputStream);
File file = new File(fileName);
InputStream fileInputStream = ZipCompression.class.getResourceAsStream(file.getName());
zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
IOUtils.copy(fileInputStream, zipOutputStream);
fileInputStream.close();
zipOutputStream.closeEntry();
if (zipOutputStream != null)
{
zipOutputStream.finish();
zipOutputStream.flush();
IOUtils.closeQuietly(zipOutputStream);
}
IOUtils.closeQuietly(bufferedOutputStream);
IOUtils.closeQuietly(byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
Byte 10 starts the file modification date and so this will always differ. See Wikipedia for the details of the zip file format.

how to convert image to byte array in java?(With out using buffered image)

Hi could anyone please explain me how to convert the image data to byte array in java I am trying like this.I do not need to use buffered image here.
File file = new File("D:/img.jpg");
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
You can convert your image data using FileInputStream also.
File file = new File("D:\\img.jpg");
FileInputStream fis = new FileInputStream(file);
//Now try to create FileInputStream which obtains input bytes from a file.
//FileInputStream is meant for reading streams of raw bytes,in this case its image data.
//For reading streams of characters, consider using FileReader.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
//Now Write to this byte array output stream
bos.write(buf, 0, readNum);
System.out.println("read " + readNum + " bytes,");
}
} catch (IOException ex) {
Logger.getLogger(ConvertImage.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] bytes = bos.toByteArray();
or you could use:
Image image = Toolkit.getDefaultToolkit().getImage("D:/img.jpg");
byte[] imageBytes = getImageBytes(image);
private byte[] getImageBytes(Image image) throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
ImageIO.write(image, "bmp", baos);
baos.flush();
return baos.toByteArray();
}
}

Java: read from binary file, send bytes over socket

This should be easy, but I can't get my head around it right now. I wanna send some bytes over a socket, like
Socket s = new Socket("localhost", TCP_SERVER_PORT);
DataInputStream is = new DataInputStream(new BufferedInputStream(s.getInputStream()));
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));
for (int j=0; j<40; j++) {
dos.writeByte(0);
}
That works, but now I dont want to writeByte to the Outputstream, but read from a binary file, then write it out. I know(?) I need a FileInputStream to read from, I just can't figure out hot to construct the whole thing.
Can someone help me out?
public void transfer(final File f, final String host, final int port) throws IOException {
final Socket socket = new Socket(host, port);
final BufferedOutputStream outStream = new BufferedOutputStream(socket.getOutputStream());
final BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(f));
final byte[] buffer = new byte[4096];
for (int read = inStream.read(buffer); read >= 0; read = inStream.read(buffer))
outStream.write(buffer, 0, read);
inStream.close();
outStream.close();
}
This would be the naive approach without proper exception handling - in a real-world setting you'd have to make sure to close the streams if an error occurs.
You might want to check out the Channel classes as well as an alternative to streams. FileChannel instances, for example, provide the transferTo(...) method that may be a lot more efficient.
Socket s = new Socket("localhost", TCP_SERVER_PORT);
String fileName = "....";
create a FileInputStream using a fileName
FileInputStream fis = new FileInputStream(fileName);
create a FileInputStream File Object
FileInputStream fis = new FileInputStream(new File(fileName));
to read from the file
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(
s.getOutputStream()));
reading from it byte after byte
int element;
while((element = fis.read()) !=1)
{
dos.write(element);
}
or reading from it buffer wise
byte[] byteBuffer = new byte[1024]; // buffer
while(fis.read(byteBuffer)!= -1)
{
dos.write(byteBuffer);
}
dos.close();
fis.close();
read a byte from the input and write the same byte to the output
or with a byte buffer it like this:
inputStream fis=new fileInputStream(file);
byte[] buff = new byte[1024];
int read;
while((read=fis.read(buff))>=0){
dos.write(buff,0,read);
}
note that you don't need to use the DataStreams for this

How To : Write a File with FileOutputStream?

What I'm doing is that the file and each line of data I'm reading for BufferOutputStream will be saved in a FileOutputStream and I want to specify the output data.
If i have understood correct, you want to download the file from S3 and write to your local directory using BufferedOutputStream .
S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
InputStream is = object.getObjectContent();
// Creating file
File file= new File(localFilePath);
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos= new BufferedOutputStream(fos);
int read = -1;
while ((read = is.read()) != -1) {
bos.write(read);
}
bos.flush();
bos.close();
is.close();

Categories

Resources