I have a strange problem with java. I want to write (amongst others) a byte[] in an ObjectOutputStream and from there to a new file. That byte-array represent an other file read from disk.
Later, after writing into the newly created file, I want to read from that file. But the byte[] which is now read from the ObjectInputStream is different from the written one.
And that is my question: WHY the heck is that byte[] different?
To make it clear and for every one to check, I wrote a short program, which will exactly show what I mean:
import java.io.*;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.security.MessageDigest;
import org.bouncycastle.util.encoders.Hex;
public class MyTest {
public static void main(String[] args) throws Exception {
// 1st step:
// ------------------------------------------------
byte[] data = openFile();
// Create file to write
FileOutputStream fos = new FileOutputStream(new File("test"));
ObjectOutputStream oosf = new ObjectOutputStream(fos);
// Write byte[]-length and byte[]
oosf.writeInt(data.length);
oosf.write(data);
// Flush & Close
fos.flush();
fos.close();
// Print hash value of saved byte[]
try {
final MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
messageDigest.reset();
System.out.println(new String(Hex.encode(messageDigest.digest(data))));
} catch (Exception e) {
}
// 2nd step
// ------------------------------------------------
// Open just saved file
FileInputStream fis = new FileInputStream(new File("test"));
ObjectInputStream ois = new ObjectInputStream(fis);
// Read the length and create a byte[]
int length = ois.readInt();
byte[] dataRead = new byte[length];
// Read the byte[] itself
ois.read(dataRead);
// Print hash value of read byte[]
try {
final MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
messageDigest.reset();
System.out.println(new String(Hex.encode(messageDigest.digest(dataRead))));
} catch (Exception e) {
}
// Both printed hash values should be the same
}
private static byte[] openFile() throws Exception {
// Download a sample file which will be converted to a byte[]
URL website = new URL("http://www.marcel-carle.de/assets/Cryptonify/Cryptonify-1.7.8.zip");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos2 = new FileOutputStream("tmp");
fos2.getChannel().transferFrom(rbc, 0, 1 << 24);
fos2.flush();
fos2.close();
// Open downloaded file and convert to byte[]
File selectedFile = new File("tmp");
FileInputStream fis1 = new FileInputStream(selectedFile);
byte[] data = new byte[(int) selectedFile.length()];
fis1.read(data);
fis1.close();
return data;
}
}
I hope you can help me!
You're ignoring exceptions; you aren't closing the right stream; and you're assuming that read() fills the buffer. Use readFully(). You aren't writing objects so you may as well use DataInputStream and DataOutputStream for this and save a little space.
Related
I've found many ways of converting a file to a byte array and writing byte array to a file on storage.
What I want is to convert java.io.File to a byte array and then convert a byte array back to a java.io.File.
I don't want to write it out to storage like the following:
//convert array of bytes into file
FileOutputStream fileOuputStream = new FileOutputStream("C:\\testing2.txt");
fileOuputStream.write(bFile);
fileOuputStream.close();
I want to somehow do the following:
File myFile = ConvertfromByteArray(bytes);
Otherwise Try this :
Converting File To Bytes
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Temp {
public static void main(String[] args) {
File file = new File("c:/EventItemBroker.java");
byte[] b = new byte[(int) file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(b);
for (int i = 0; i < b.length; i++) {
System.out.print((char)b[i]);
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
e.printStackTrace();
}
catch (IOException e1) {
System.out.println("Error Reading The File.");
e1.printStackTrace();
}
}
}
Converting Bytes to File
public class WriteByteArrayToFile {
public static void main(String[] args) {
String strFilePath = "Your path";
try {
FileOutputStream fos = new FileOutputStream(strFilePath);
String strContent = "Write File using Java ";
fos.write(strContent.getBytes());
fos.close();
}
catch(FileNotFoundException ex) {
System.out.println("FileNotFoundException : " + ex);
}
catch(IOException ioe) {
System.out.println("IOException : " + ioe);
}
}
}
I think you misunderstood what the java.io.File class really represents. It is just a representation of the file on your system, i.e. its name, its path etc.
Did you even look at the Javadoc for the java.io.File class? Have a look here
If you check the fields it has or the methods or constructor arguments, you immediately get the hint that all it is, is a representation of the URL/path.
Oracle provides quite an extensive tutorial in their Java File I/O tutorial, with the latest NIO.2 functionality too.
With NIO.2 you can read it in one line using java.nio.file.Files.readAllBytes().
Similarly you can use java.nio.file.Files.write() to write all bytes in your byte array.
UPDATE
Since the question is tagged Android, the more conventional way is to wrap the FileInputStream in a BufferedInputStream and then wrap that in a ByteArrayInputStream.
That will allow you to read the contents in a byte[]. Similarly the counterparts to them exist for the OutputStream.
You can't do this. A File is just an abstract way to refer to a file in the file system. It doesn't contain any of the file contents itself.
If you're trying to create an in-memory file that can be referred to using a File object, you aren't going to be able to do that, either, as explained in this thread, this thread, and many other places..
Apache FileUtil gives very handy methods to do the conversion
try {
File file = new File(imagefilePath);
byte[] byteArray = new byte[file.length()]();
byteArray = FileUtils.readFileToByteArray(file);
}catch(Exception e){
e.printStackTrace();
}
There is no such functionality but you can use a temporary file by File.createTempFile().
File temp = File.createTempFile(prefix, suffix);
// tell system to delete it when vm terminates.
temp.deleteOnExit();
You cannot do it for File, which is primarily an intelligent file path. Can you refactor your code so that it declares the variables, and passes around arguments, with type OutputStream instead of FileOutputStream? If so, see classes java.io.ByteArrayOutputStream and java.io.ByteArrayInputStream
OutputStream outStream = new ByteArrayOutputStream();
outStream.write(whatever);
outStream.close();
byte[] data = outStream.toByteArray();
InputStream inStream = new ByteArrayInputStream(data);
...
1- Traditional way
The traditional conversion way is through using read() method of InputStream as the following:
public static byte[] convertUsingTraditionalWay(File file)
{
byte[] fileBytes = new byte[(int) file.length()];
try(FileInputStream inputStream = new FileInputStream(file))
{
inputStream.read(fileBytes);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return fileBytes;
}
2- Java NIO
With Java 7, you can do the conversion using Files utility class of nio package:
public static byte[] convertUsingJavaNIO(File file)
{
byte[] fileBytes = null;
try
{
fileBytes = Files.readAllBytes(file.toPath());
}
catch (Exception ex)
{
ex.printStackTrace();
}
return fileBytes;
}
3- Apache Commons IO
Besides JDK, you can do the conversion using Apache Commons IO library in 2 ways:
3.1. IOUtils.toByteArray()
public static byte[] convertUsingIOUtils(File file)
{
byte[] fileBytes = null;
try(FileInputStream inputStream = new FileInputStream(file))
{
fileBytes = IOUtils.toByteArray(inputStream);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return fileBytes;
}
3.2. FileUtils.readFileToByteArray()
public static byte[] convertUsingFileUtils(File file)
{
byte[] fileBytes = null;
try
{
fileBytes = FileUtils.readFileToByteArray(file);
}
catch(Exception ex)
{
ex.printStackTrace();
}
return fileBytes;
}
Server side
#RequestMapping("/download")
public byte[] download() throws Exception {
File f = new File("C:\\WorkSpace\\Text\\myDoc.txt");
byte[] byteArray = new byte[(int) f.length()];
byteArray = FileUtils.readFileToByteArray(f);
return byteArray;
}
Client side
private ResponseEntity<byte[]> getDownload(){
URI end = URI.create(your url which server has exposed i.e. bla
bla/download);
return rest.getForEntity(end,byte[].class);
}
public static void main(String[] args) throws Exception {
byte[] byteArray = new TestClient().getDownload().getBody();
FileOutputStream fos = new
FileOutputStream("C:\\WorkSpace\\testClient\\abc.txt");
fos.write(byteArray);
fos.close();
System.out.println("file written successfully..");
}
//The file that you wanna convert into byte[]
File file=new File("/storage/0CE2-EA3D/DCIM/Camera/VID_20190822_205931.mp4");
FileInputStream fileInputStream=new FileInputStream(file);
byte[] data=new byte[(int) file.length()];
BufferedInputStream bufferedInputStream=new BufferedInputStream(fileInputStream);
bufferedInputStream.read(data,0,data.length);
//Now the bytes of the file are contain in the "byte[] data"
/*If you want to convert these bytes into a file, you have to write these bytes to a
certain location, then it will make a new file at that location if same named file is
not available at that location*/
FileOutputStream fileOutputStream =new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()+"/Video.mp4");
fileOutputStream.write(data);
/* It will write or make a new file named Video.mp4 in the "Download" directory of
the External Storage */
I am trying to encrypt a zip file with a password using AES-256 encryption. Below is the code that I am running.
import java.io.*;
import java.security.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
public class Main {
public static void encryptAndClose(FileInputStream fis, FileOutputStream fos)
throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
// Length is 16 byte
SecretKeySpec sks = new SecretKeySpec("1234567890123456".getBytes(), "AES");
// Create cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sks);
// Wrap the output stream for encoding
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
//wrap output with buffer stream
BufferedOutputStream bos = new BufferedOutputStream(cos);
//wrap input with buffer stream
BufferedInputStream bis = new BufferedInputStream(fis);
// Write bytes
int b;
byte[] d = new byte[8];
while((b = bis.read(d)) != -1) {
bos.write(d, 0, b);
}
// Flush and close streams.
bos.flush();
bos.close();
bis.close();
}
public static void decryptAndClose(FileInputStream fis, FileOutputStream fos)
throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
SecretKeySpec sks = new SecretKeySpec("1234567890123456".getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sks);
CipherInputStream cis = new CipherInputStream(fis, cipher);
//wrap input with buffer stream
BufferedInputStream bis = new BufferedInputStream(cis);
//wrap output with buffer stream
BufferedOutputStream bos = new BufferedOutputStream(fos);
int b;
byte[] d = new byte[8];
while((b = bis.read(d)) != -1) {
bos.write(d, 0, b);
}
bos.flush();
bos.close();
bis.close();
}
static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException {
if (fileToZip.isHidden()) {
return;
}
if (fileToZip.isDirectory()) {
if (fileName.endsWith("/")) {
zipOut.putNextEntry(new ZipEntry(fileName));
zipOut.closeEntry();
} else {
zipOut.putNextEntry(new ZipEntry(fileName + "/"));
zipOut.closeEntry();
}
File[] children = fileToZip.listFiles();
for (File childFile : children) {
zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
}
return;
}
FileInputStream fis = new FileInputStream(fileToZip);
ZipEntry zipEntry = new ZipEntry(fileName);
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
static void unZipFile(ZipEntry zipEntry,File destDir,ZipInputStream zis, byte[] buffer) throws IOException{
while (zipEntry != null) {
File newFile = newFile(destDir, zipEntry);
if (zipEntry.isDirectory()) {
if (!newFile.isDirectory() && !newFile.mkdirs()) {
throw new IOException("Failed to create directory " + newFile);
}
} else {
// fix for Windows-created archives
File parent = newFile.getParentFile();
if (!parent.isDirectory() && !parent.mkdirs()) {
throw new IOException("Failed to create directory " + parent);
}
// write file content
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
zipEntry = zis.getNextEntry();
}
}
public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
File destFile = new File(destinationDir, zipEntry.getName());
String destDirPath = destinationDir.getCanonicalPath();
String destFilePath = destFile.getCanonicalPath();
if (!destFilePath.startsWith(destDirPath + File.separator)) {
throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
}
return destFile;
}
public static void main(String[]args) {
//compress to zip.
String sourceFile = "C:\\test";
FileOutputStream fos;
try {
fos = new FileOutputStream("C:\\test\\test.zip");
ZipOutputStream zipOut = new ZipOutputStream(fos);
File fileToZip = new File(sourceFile);
zipFile(fileToZip, fileToZip.getName(), zipOut);
zipOut.close();
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//encrypt the zip.
String outDir = "C:/test";
String outFilename = "test-encrypt.zip";
String inDir = "C:/test";
String inFilename = "test.zip";
File output= new File(outDir, outFilename);
File input= new File(inDir, inFilename);
if (input.exists()) {
System.out.println("test");
FileInputStream inStream;
try {
inStream = new FileInputStream(input);
FileOutputStream outStream = new FileOutputStream(output);
encryptAndClose(inStream, outStream);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The intent of the code is to create a zip file then encrypt the generated zip file with AES.
The code can successfully generate a zip file that can be zipped and unzipped with WinZip or 7zip.
However, when it tries to encrypt the generated zip file, the code instead causes the file (e.g.test-encrypt.zip) to be corrupted and cannot be opened by programs like WinZip or 7zip.
I wish to do this without using zip4j if possible. Is there any problem with my code or understanding of the code?
This is my first time working with encryption and any help would be much appreciated!
If you create a ZIP first, and then encrypt the ZIP file using AES algorithm or whatever algorithm, the output file won't remain a ZIP.
It won't be following the ZIP standard format.
So, it won't be possible to unzip.
You need to first Decrypt the file and get back the original ZIP, and then only that original zip can be opened/unzipped using any wellknown zip handling software.
Encrypting a ZIP file will result in the bytes inside the file changed, which will result in the software not recognizing the file header, necessary ZipEntry record structure, etc.
The best option is to provide a password at the time of creating the zip, so that it cannot be unzipped without a password.
OR
Encrypt the original files, and then put the encrypted files inside the Zip. But, don't encrypt the ZIP file.
Java does not support zip file encryption. Anyway, it supports very limited activities with zip files. You have to try to make you work with zip file much more easy. E.g. you can check zip4jvm
Create (or open existed) zip archive and add some regular files and/or directories with AES 256bit encryption.
Path zip = Paths.get("filename.zip");
Collection<Path> paths = Arrays.asList(
Paths.get("/bikes/ducati-panigale-1199.jpg"),
Paths.get("/bikes/honda-cbr600rr.jpg"),
Paths.get("/cars"),
Paths.get("/saint-petersburg.jpg"));
ZipEntrySettings settings = ZipEntrySettings.builder()
.encryption(Encryption.AES_256, "password".toCharArray())
.build();
ZipIt.zip(zip).entrySettings(settings).add(paths);
To get more details about AES encryptions in zip you can check AesEncoder.java
This is a simplified version of my program.
I have a Server.java file where I read in "b.txt" into a byte array and then write it to the DataOutputStream.
import java.io.*;
import java.net.*;
class Server {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(4000);
Socket s = ss.accept();
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
byte[] byteArray = new byte[32];
File tempFile = new File("Files/b.txt");
FileInputStream fis = new
FileInputStream(tempFile);
fis.read(byteArray);
fis.close();
dout.write(byteArray);
dout.flush();
dout.close();
s.close();
} catch (Exception e) {
//handle exceptions
}
}
}
In Client.java I read the DataInputStream into a byteArray. Then, I create a FileOutputStream. In the commented out code fos.write(byteArray), this writes to the file, however since the actual file may not be exactly 32 bytes I am left with a corrupt file since the remaining bytes just get filled with random data (or whatever happens).
import java.io.*;
import java.net.*;
class Client {
public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 4000);
DataInputStream din = new DataInputStream(s.getInputStream());
byte[] byteArray = new byte[32];
FileOutputStream fos = new FileOutputStream("Downloaded/testfile.txt");
//fos.write(byteArray);
int count;
while ((count = din.read(byteArray)) > 0) {
fos.write(byteArray, 0, count);
}
fos.close();
din.close();
s.close();
} catch (Exception e) {
//handle exceptions
}
}
}
So I looked up how to fix this and a lot of places told me to do the code I have inside the while loop: while ((count = din.read... etc.
However when I try this, testfile.txt is blank and contains 0 bytes. Am I missing something big here? I have tried sending in the correct amount of bytes from the server, however this doesn't change anything.
I would like to be able to transfer any file type, so it is important that I am able to transfer the correct amount of bytes without corrupting the data by having bytes "hanging over". Thank you.
I'm new to java and need some understanding on below.
private static void decompressGzipFile(String gzipFile, String newFile) {
try {
FileInputStream fis = new FileInputStream(gzipFile);
GZIPInputStream gis = new GZIPInputStream(fis);
FileOutputStream fos = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int len;
while((len = gis.read(buffer)) != -1){
fos.write(buffer, 0, len);
}
//close resources
System.out.println("Decompression is successful");
fos.close();
gis.close();
} catch (IOException e) {
e.printStackTrace();
}
I have some data in compressed GZIP file which is in
í?]o£F ?s?_1RoZ?Öó?¹Ã?d¬ÅÆ[1]?U.?¦Q?8²?Dù÷=?íÄÃÌ ?VUUÎM´d Î?÷|Ì?Í?7ÉöaõÇjûzö³
?9 ??Á¤?? ?? fs?c?;î&Äq?3?Ú?>ÙËv·Ü t¶Y¯w¦uM¿ÿ?Z²?Æò?
________________________________________
[hº~Biþ?F
________________________________________
ÎÁ?bâ??OÃÙ[1]Yã0ó'Q?¬?x?¡ ?â
This is byte data and how can I convert this to string format or readable format in java?
I tried using GZip Uncompressor to read this file but that give me the same file as output but I want the data to be in human readable format. I tried using GZIPInputStream and base64inputStream but that gives incorrect data type. I'm not sure if this is really byte data or how to read this data? any suggestions please help
FileOutputStream bydefault writes data into files using encoding.
If you want to skip encoding , use BufferedReader
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
public class ZipFileReader{
public static void main(String[] args) throws IOException {
GZIPInputStream zipFile = new GZIPInputStream(new FileInputStream("C:/Users/HimanshuSharma2/Downloads/phayes-geoPHP-1.2-20-g6855624.tar.gz"));
BufferedReader br = new BufferedReader(new InputStreamReader(zipFile));
String content;
while ((content = br.readLine()) != null)
System.out.println(content);
}
}
checked on sample file from this link: https://github.com/phayes/geoPHP/tarball/master
and finally write this string into file.
Basically i compress video using the customized compressor class in Java. I have assembled my complete code snippets here. My actually problem is, generated video [ A.mp4] from the decompressed byte array is not running. I actually i got this compressor class code over the internet. As i new to Java platform, i am struggling to resolve this problem. Could you please any one help me on this.?
public class CompressionTest
{
public static void main(String[] args)
{
Compressor compressor = new Compressor();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis=null;
File file=null;
try
{
URL uri=CompressionTest.class.getResource("/Files/Video.mp4");
file=new File(uri.getPath());
fis = new FileInputStream(file);
}
catch ( FileNotFoundException fnfe )
{
System.out.println( "Unable to open input file");
}
try
{
byte[] videoBytes = getBytesFromFile(file);
System.out.println("CompressionVideoToCompress is: '" +videoBytes + "'");
byte[] bytesCompressed = compressor.compress(videoBytes);
System.out.println("bytesCompressed is: '" +bytesCompressed+ "'");
byte[] bytesDecompressed=compressor.decompress(bytesCompressed);
System.out.println("bytesDecompressed is: '" +bytesDecompressed+ "'");
FileOutputStream out = new FileOutputStream("A.mp4");
out.write(bytesDecompressed,0,bytesDecompressed.length-1);
out.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
System.out.println("bytesCompressed is: '");
}
}
public static byte[] getBytesFromFile(File file) throws IOException
{
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[1064];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0)
{
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}
}
class Compressor
{
public Compressor()
{}
public byte[] compress(byte[] bytesToCompress)
{
Deflater deflater = new Deflater();
deflater.setInput(bytesToCompress);
deflater.finish();
byte[] bytesCompressed = new byte[Short.MAX_VALUE];
int numberOfBytesAfterCompression = deflater.deflate(bytesCompressed);
byte[] returnValues = new byte[numberOfBytesAfterCompression];
System.arraycopy
(
bytesCompressed,
0,
returnValues,
0,
numberOfBytesAfterCompression
);
return returnValues;
}
public byte[] decompress(byte[] bytesToDecompress)
{
Inflater inflater = new Inflater();
int numberOfBytesToDecompress = bytesToDecompress.length;
inflater.setInput
(
bytesToDecompress,
0,
numberOfBytesToDecompress
);
int compressionFactorMaxLikely = 3;
int bufferSizeInBytes =
numberOfBytesToDecompress
* compressionFactorMaxLikely;
byte[] bytesDecompressed = new byte[bufferSizeInBytes];
byte[] returnValues = null;
try
{
int numberOfBytesAfterDecompression = inflater.inflate(bytesDecompressed);
returnValues = new byte[numberOfBytesAfterDecompression];
System.arraycopy
(
bytesDecompressed,
0,
returnValues,
0,
numberOfBytesAfterDecompression
);
}
catch (DataFormatException dfe)
{
dfe.printStackTrace();
}
inflater.end();
return returnValues;
}
}
I've tested your code by compressing and decompressing a simple TXT file. The code is broken, since the compressed file, when uncompressed, is different from the original one.
Take for granted that the code is broken at least in the getBytesFromFile function. Its logic is tricky and troublesome, since it only allows files up to length 1064 and the check (throwing IOException when a longer file is read) does not work at all. The file gets read only partially and no exception is thrown.
What you are trying to achieve (file compression/decompression) can be done this way. I've tested it and it works, you just need this library.
import java.io.*;
import java.util.zip.*;
import org.apache.commons.io.IOUtils; // <-- get this from http://commons.apache.org/io/index.html
public class CompressionTest2 {
public static void main(String[] args) throws IOException {
File input = new File("input.txt");
File output = new File("output.bin");
Compression.compress(input, output);
File input2 = new File("input2.txt");
Compression.decompress(output, input2);
// At this point, input.txt and input2.txt should be equal
}
}
class Compression {
public static void compress(File input, File output) throws IOException {
FileInputStream fis = new FileInputStream(input);
FileOutputStream fos = new FileOutputStream(output);
GZIPOutputStream gzipStream = new GZIPOutputStream(fos);
IOUtils.copy(fis, gzipStream);
gzipStream.close();
fis.close();
fos.close();
}
public static void decompress(File input, File output) throws IOException {
FileInputStream fis = new FileInputStream(input);
FileOutputStream fos = new FileOutputStream(output);
GZIPInputStream gzipStream = new GZIPInputStream(fis);
IOUtils.copy(gzipStream, fos);
gzipStream.close();
fis.close();
fos.close();
}
}
This code doesn't come from "credible and/or official sources" but at least it works. :)
Moreover, in order to get more answers, adjust the title stating your real problem: your compressed files don't decompress the right way. There is no 'video' stuff here. Moreover, zipping a .mp4 file is no achievement (compression ratio will likely be around 99.99%).
Two tips:
1) Replace getBytesFromFile with a well known API call, either using Apache commons (IOUtils) or java 7 now provides such a method, too.
2) Test compress and decompress by writing a Junit test:
Create a random huge byte array, write it out, read it back and compare it with the created one.