How to convert byte data to readable text in Java - java

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.

Related

Convert mp4 to bytes and bytes to mp4 in java for android [duplicate]

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 */

Decoding base64 data and not able to download as a file

Am getting base64 encoded data as String format. Am trying to decode the base64 and want to download as a file. I have commented the below few lines of code, where am getting error out of those line.
Am not sure how to decode the data.
String contentByte=null;
for (SearchHit contenthit : contentSearchHits) {
Map<String, Object> sourceAsMap = contenthit.getSourceAsMap();
fileName=sourceAsMap.get("Name").toString();
System.out.println("FileName ::::"+fileName);
contentByte = sourceAsMap.get("resume").toString();
}
System.out.println("Bytes --->"+contentByte);
File file = File.createTempFile("Testing",".pdf", new File("D:/") );
file.deleteOnExit();
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(Base64.getDecoder().decode(contentByte)); //getting error on this line
Please find the below compilation error am getting.
The method write(int) in the type BufferedWriter is not applicable for the arguments (byte[])
Am using Java 8 version
Writers are used for writing characters, not bytes. To write bytes, you should use some flavor of OutputStream. See Writer or OutputStream?
But if all you want is to write a byte array to a file, Files class provides a Files.write method that does just that:
byte[] bytes = Base64.getDecoder().decode(contentByte);
Files.write(file.toPath(), bytes);
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class Example {
public static void main(String[] args) {
String contentByte="Simple text send from server";
byte[] bytes =
Base64.getEncoder().encode(contentByte.getBytes(StandardCharsets.UTF_8));
//Data received by you at server end(base64 encoded data as string)
contentByte = new String(bytes);
System.out.println(new String(bytes));
BufferedWriter out = null;
System.out.println("Bytes --->"+contentByte);
try {
File file = File.createTempFile("Testing",".pdf", new File("/tmp/") );
// file.deleteOnExit(); // this line will remove file and your data will not going to save to file. So remove this line.
out = new BufferedWriter(new FileWriter(file));
byte[] decodedImg =
Base64.getDecoder().decode(contentByte.getBytes(StandardCharsets.UTF_8));
out.write(new String(decodedImg)); //getting error on this line
}catch (Exception e)
{
e.printStackTrace();
}finally {
if(out!=null)
{
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Might above solution with help you.

Is it possible to convert a zip file to binary file to load into BLOB

I have to upload a zip file into BLOB using informatica, for this task, I am using java transformation. Using the following code, I was able to upload all the flat files and retrieve them from the database table in correct format.
This code is not working for zip files. Can you please suggest me on how to convert a zip file into a binary file so that it can be inserted into BLOB?
byte bytes[] = null;
File f1 = new File(TARGETFILE);
try (FileInputStream fis = new FileInputStream(f1)) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
byte[] buffer = new byte[1024];
int read = -1;
while ((read = fis.read(buffer)) != -1) {
baos.write(buffer, 0, read);
    }
bytes = baos.toByteArray();
FILE_CONTENT=bytes;
FILE_SIZE=Double.toString(f1.length()/1024*1024);
}
catch(Exception e1) {
}
}
catch (IOException exp) {
exp.printStackTrace();
}
A very simple version, just converts the data to a hex print. Using these parts you should be able to get to binary no problem. Just save the conversion to memory rather then print the string.
package test;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
/**
*
* #author User
*/
public class Test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
File file = new File("C:\\Users\\User\\Downloads\\ltc1298-arduino-library-master.zip");
byte[] bytes = new byte[(int)file.length()];
try {
DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(new FileInputStream("C:\\Users\\User\\Downloads\\ltc1298-arduino-library-master.zip")));
dataInputStream.readFully(bytes);
System.out.println(String.format(Arrays.toString(bytes)));
for (byte b : bytes) {
System.out.format("0x%x ", b);
}
dataInputStream.close();
}
catch (Exception e) {
System.out.println("Error");
e.printStackTrace();
}
}
}

Read different byte[] from ObjectInputStream than written to ObjectOutputStream

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.

Transform InputStream to FileItem in Java

How can I do to transform from InputStream to FileItem in Java?
Thanks.
Here is a working example. Note that you must change the InputStream from the example with your InputStream, and also you might want to change the location of your work/tmp dir().
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
public class TestFile {
public static void main(String args[]) throws IOException {
// This is a sample inputStream, use your own.
InputStream inputStream = new FileInputStream("c:\\Kit\\Apache\\geronimo-tomcat6-javaee5-2.1.6\\README.txt");
int availableBytes = inputStream.available();
// Write the inputStream to a FileItem
File outFile = new File("c:\\tmp\\newfile.xml"); // This is your tmp file, the code stores the file here in order to avoid storing it in memory
FileItem fileItem = new DiskFileItem("fileUpload", "plain/text", false, "sometext.txt", availableBytes, outFile); // You link FileItem to the tmp outFile
OutputStream outputStream = fileItem.getOutputStream(); // Last step is to get FileItem's output stream, and write your inputStream in it. This is the way to write to your FileItem.
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
// Don't forget to release all the resources when you're done with them, or you may encounter memory/resource leaks.
inputStream.close();
outputStream.flush(); // This actually causes the bytes to be written.
outputStream.close();
// NOTE: You may also want to delete your outFile if you are done with it and dont want to take space on disk.
}
}

Categories

Resources