Convert Zip byte[] to Unzip byte[] using java code [duplicate] - java

This question already has answers here:
convert zip byte[] to unzip byte[]
(4 answers)
Closed 5 years ago.
Could some one help me with the code snippet in converting zip byte[] to unzip byte[] in memory with out writing to a file intermediary
I looked in to this stack overflow "convert zip byte[] to unzip byte[]' but not able to get it using java code
Thanks
Somu

Here are the tools you need for that:
ByteArrayInputStream - allows you to wrap an array of bytes as a stream.
ZipInputStream - reads the zipped stream of bytes and presents them as unzipped ones.
ByteArrayOutputStream - a stream that writes into internal byte buffer.
(If using Java 9) InputStream#transferTo - copy from input stream to output stream. (If not using Java 9) Copy it manually
ByteArrayOutputStream#toByteArray - extract buffer from the output stream.
Wire them all together and you are done.

Related

Read an integer from a binary file [duplicate]

This question already has answers here:
Does Java flip byte order in file I/O? [duplicate]
(2 answers)
how can i read from a binary file?
(3 answers)
Closed 2 years ago.
I need to read an integer from a non-text file in Java. Here is the equivalent code in C
unsigned int MagicNumber;
int fd = open("MyFile", O_RDONLY);
int rc = read(fd, &MagicNumber, 4);
What is the equivalent in Java?
This does NOT work for me (it produces different results than the C code):
FileInputStream fin = new FileInputStream("MyFile");
DataInputStream din = new DataInputStream(fin);
int MagicNumber = din.readInt();
Java uses a machine independent representation of the interger as a byte sequence, if you write it with DataOutputStream and next try to read it with DataInputStream on a different machine even with different endian, it will read it correctly anyway.
Java was designed exactly for that: i.e. to be machine independent.
Of course you cannot assume the byte sequence will be the same in the file you generated in C.
It happens that Java defaults to big-endian (see the DataOutput specs).
If you do your test on any big-endian machine it will work, on a little-endian (like x86) it will fail.
You can try to use LittleEndianDataOutputStream to solve this.

File split in java [duplicate]

This question already has answers here:
Java - Read file and split into multiple files
(11 answers)
Closed 4 years ago.
How can I split a file in two ( file1 and file2 ) such that the file1 contains first 10kb of the file and file2 contains rest of the remaining data of the file.
I am using AIDE on android.
There is no "system call" to split a file. You need to open a file, read it and copy the contents to the corresponding output files (which you need to create).
Synopsis:
Open the input file as a FileInputStream
Make a byte[] buffer somewhere around 4k
Open the two output files as two FileOutputStreams
Read from input into buffer and write buffer to first OutputStream
Do this until exactly 10kb bytes have been read and written
Read from input into buffer and write buffer to second OutputStream
Do this until there are no more bytes from the input stream
Close all three streams
Of course, you will need to be careful to make sure that you copy exactly the correct number of bytes. See InputStream.read(buf, offset, length) for details. Test also for special case when input file is less than 10k long.

When should we use BufferedInputStream,FileInputStream or DataInputStream? [duplicate]

This question already has answers here:
Should I use DataInputStream or BufferedInputStream
(7 answers)
Closed 5 years ago.
I'm confused the above mentioned classes. When to use what? From my perspective every thing that comes in, is in the form of stream in java right? so which one is to use in what case to make the input more efficient? Also answer please can I use DataInputStream or BufferedInputStream in case of reading content from files?
FileInputStream
Is used for reading from files.
See the JavaDoc:
A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. [...]
DataInputStream
Is used for reading in primitive Java types (that you might have written using a DataOutputStream) and provides convenience methods for that purpose, e.g. writeInt().
See the JavaDoc:
A data input stream lets an application read primitive Java data types
from an underlying input stream in a machine-independent way. [...]
BufferedInputStream
Is used to do buffered block reads from an InputStream (instead of single bytes) and increases performance if reading small chunks of data. Most of the time you want to use it for text processing.
See the JavaDoc:
A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input[...].
Of course you can combine those as they are following the Decorator Pattern.
Example of writing primitive Java types to a file:
FileOutputStream write = new FileOutputStream
DataOutputStream out = new DataOutputStream(write);
out.writeInt(10);
write.close();

Java file handling classes [duplicate]

This question already has answers here:
What's the difference between InputStream and ByteArrayInputStream?
(4 answers)
Closed 6 years ago.
What is the difference between FileInputStream and ByteArrayInputStream?
When we should use them?
What is the benefits of using one over other
Streams
byte oriented stream (8 bit)
good for binary data such as a Java .class file, images etc.
good for "machine-oriented"
Readers/Writers
char (utf-16) oriented stream (16 bit)
one character at a time
good for text such as a Java source
good for "human-oriented" data
Buffered
many bytes/characters at a time
always useful unless proven otherwise
Both ByteArrayInputStream and FileInputStream serve the same purpose i.e. reading binary data and both implement a common abstract superclass InputStream.So it is really tough find out a sharp contrast among the two.But common logic dictates that arrays are already present in the memory hence they can be accessed much faster as compared to files which are present in the file system. Also if you go through the documentation of the two classes you will find out that read function of ByteArrayInputStream cannot block whereas the read function in FileInputStream blocks if no input is yet available.
So if you are confused about what to use when then think about these :
In what form my data is present, file or array?
Is speed really a requirement? If it is, then go for ByteArray. But remember you cannot store too much information in ByteArray as they are present in the memory.

How to convert byte array in String format to byte array?

I have created a byte array of a file.
FileInputStream fileInputStream=null;
File file = new File("/home/user/Desktop/myfile.pdf");
byte[] bFile = new byte[(int) file.length()];
try {
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
}catch(Exception e){
e.printStackTrace();
}
Now,I have one API, which is expecting a json input, there I have to put the above byte array in String format. And after reading the byte array in string format, I need to convert it back to byte array again.
So, help me to find;
1) How to convert byte array to String and then back to the same byte array?
The general problem of byte[] <-> String conversion is easily solved once you know the actual character set (encoding) that has been used to "serialize" a given text to a byte stream, or which is needed by the peer component to accept a given byte stream as text input - see the perfectly valid answers already given on this. I've seen a lot of problems due to lack of understanding character sets (and text encoding in general) in enterprise java projects even with experienced software developers, so I really suggest diving into this quite interesting topic. It is generally key to keep the character encoding information as some sort of "meta" information with your binary data if it represents text in some way. Hence the header in, for example, XML files, or even suffixes as parts of file names as it is sometimes seen with Apache htdocs contents etc., not to mention filesystem-specific ways to add any kind of metadata to files. Also, when communicating via, say, http, the Content-Type header fields often contain additional charset information to allow for correct interpretation of the actual Contents.
However, since in your example you read a PDF file, I'm not sure if you can actually expect pure text data anyway, regardless of any character encoding.
So in this case - depending on the rest of the application you're working on - you may want to transfer binary data within a JSON string. A common way to do so is to convert the binary data to Base64 and, once transferred, recover the binary data from the received Base64 string.
How do I convert a byte array to Base64 in Java?
is a good starting point for such a task.
String class provides an overloaded constructor for this.
String s = new String(byteArray, "UTF-8");
byteArray = s.getBytes("UTF-8");
Providing an explicit encoding charset is encouraged because different encoding schemes may have different byte representations. Read more here and here.
Also, your inputstream maynot read all the contents in one go. You have to read in a loop until there is nothing more left to be read. Read the documentation. read() returns the number of bytes read.
Reads up to b.length bytes of data from this input stream into an
array of bytes. This method blocks until some input is available
String.getBytes() and String(byte[] bytes) are methods to consider.
Convert byte array to String
String s = new String(bFile , "ISO-8859-1" );
Convert String to byte array
byte bArray[] =s.getBytes("ISO-8859-1");

Categories