String base64Code = dataInputStream.readUTF();
byte[] decodedString = null;
decodedString = Base64.decodeBase64(base64Code);
FileOutputStream imageOutFile = new FileOutputStream(
"E:/water-drop-after-convert.jpg");
imageOutFile.write(decodedString);
imageOutFile.close();
The problem is the data is transferred completely and if the data is in text format it is displayed correctly however when i am trying to decode image and write it on output file,it doesnt simply show up in photo viewer.
Any help would be highly appreciated
DataInputStream.readUTF may be the issue. This method assumes that the text was written to the file by DataOutputStream.writeUTF. If it is not so, and you are going to read a regular text, choose a different class, like BufferedReader or Scanner. Or Java 1.7's Files.readAllBytes.
Once I had to convert the Image into base 64 and sent that image as stream (encoding and decoding stuff here is the code)
To Convert a file into base64 :
String filePath = "E:\\water-drop-after-convert.jpg";
File bMap = new File(filePath);
byte[] bFile = new byte[(int) bMap.length()];
FileInputStream fileInputStream = null;
String imageFileBase64 = null;
try {
fileInputStream = new FileInputStream(bMap);
fileInputStream.read(bFile);
fileInputStream.close();
imageFileBase64 = Base64.encode(bFile);
}catch(Exception e){
e.printStackTrace();
}
then on service side I did thing like that to convert image in base 64 String back into file, so that i can display.
I had used this library on server side import sun.misc.BASE64Decoder;
//filePath is where you wana save image
String filePath = "E:\\water-drop-after-convert.jpg";
File imageFile = new File(filePath);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(imageFile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = null;
try {
decodedBytes = decoder.decodeBuffer(imageFileBase64);//taking input string i.e the image contents in base 64
} catch (IOException e1) {
e1.printStackTrace();
}
try {
fos.write(decodedBytes);
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
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 */
Hi guys i trying to convert a pdf file to byte array but it dosn't work for me when i trying to get the file from the classPath resource using the classLoader and after that transform it to byte array it doesn't work i don't have a null array but the getting array length it's not ok and when i write this byte array as a file i have an damaged file and i can't opend it.
A last thing when i trying to get the file using the path like (c://java//files//test.pdf) it's working and byte array length it's ok and when i write the array as a file i have exactly the some file in input. another thing the getting file length using classLoader and using path is exactly the some
My code is :
public static void main(String[] args) {
try {
// convert file to byte[]
byte[] bFile = readBytesFromFile("C:\\TEMP\\test.pdf");
byte[] bytes = readBytesFromFileResources();
System.out.println(bFile.length);//60255
System.out.println(bytes.length);//14463
}
private static byte[] readBytesFromFile(String filePath) {
FileInputStream fileInputStream = null;
byte[] bytesArray = null;
try {
File file = new File(filePath);
bytesArray = new byte[(int) file.length()];
//read file into bytes[]
fileInputStream = new FileInputStream(file);
fileInputStream.read(bytesArray);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bytesArray;
}
private static byte[] readBytesFromFileResources() {
ClassLoader classLoader = ReadFile.class.getClassLoader();
File file = new File(classLoader.getResource("test.pdf").getFile());
FileInputStream fileInputStream = null;
byte[] bytesArray = null;
try {
bytesArray = new byte[(int) file.length()];
//read file into bytes[]
fileInputStream = new FileInputStream(file);
fileInputStream.read(bytesArray);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bytesArray;
}
A last thing when i trying to get the file using the path like
(c://java//files//test.pdf) it's working and byte array length it's ok
and when i write the array as a file i have exactly the some file in
input.
c://java//files//test.pdf is probably not in the classpath.
So, you cannot use the classloader to load the file as the classloader will not be able to find it.
Either you move the file in the classpath (if it makes sense), either you load the file with the filesystem dependent way as you write in your question :
File file = new file("c://java//files//test.pdf)";
I am downloading the generated ics calendar, while downloading the ics calendar it is downloading name like a "ics". I am trying to add name like "test.ics", But i am not able to add the name. please help me to add name dynamically to the downloaded the ics file. Using below code to convert ics file to bytes.
private byte[] calendarAsByteArray(net.fortuna.ical4j.model.Calendar calendar) throws FileNotFoundException {
byte[] bytes;
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
CalendarOutputter outputter = new CalendarOutputter();
outputter.setValidating(false);
outputter.output(calendar, output);
bytes = output.toByteArray();
} catch (Exception e) {
throw new IllegalStateException("can't convert calendar to bytes: "+e);
}
return bytes;
}
You can write your bytes array to file and specify filename you want:
private byte[] calendarAsByteArray(net.fortuna.ical4j.model.Calendar calendar) throws FileNotFoundException {
byte[] bytes;
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
CalendarOutputter outputter = new CalendarOutputter();
outputter.setValidating(false);
outputter.output(calendar, output);
bytes = output.toByteArray();
FileOutputStream fos = new FileOutputStream("test.ics");
fos.write(bytes);
fos.close()
} catch (Exception e) {
throw new IllegalStateException("can't convert calendar to bytes: "+e);
}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IgLz4NCiAgICA8SXRlbSBOYW1lPSJGbGFnIiBWYWx1ZT0iMCIgLz4NCiAg
ICA8SXRlbSBOYW1lPSJSZXRhaW5JbWFnZSIgVmFsdWU9Ik5vIiAvPg0KICAgIDxJdGVtIE5hbWU9
IlJldGFpbk9yaWdpbmFsIiBWYWx1ZT0iRG8gTm90IFJldGFpbiIgLz4NCiAgICA8SXRlbSBOYW1l
PSJTb3VyY2UiIFZhbHVlPSJJTkRFWEVEIiAvPg0KICA8L0l0ZW1zPg0KICA8Um91dGU+DQogICAg
PHRvIC8+DQogICAgPGNjIC8+DQogICAgPE5vdGUgLz4NCiAgPC9Sb3V0ZT4NCjwvUm9vdD4=
I need to be able to take those base 64 charecters from the text file and output a new XML File. Currently, the InputStream is not being correctly converted to base 64
public static void main(String[] args) {
try {
File file = new File("C:\\Users\\khurt\\Desktop\\xml.txt");
InputStream myScan = new FileInputStream(file);
byte[] b = new byte[(int)file.length()];
myScan.read(b);
String cowo = myScan.toString();
String decoded = DatatypeConverter.printBase64Binary(b);
String cat = b.toString();
System.out.println(decoded);
byte[] bArray = cat.getBytes();
OutputStream out = new FileOutputStream("C:\\Users\\gdfurt\\Desktop\\cow.xml");
out.write(b);
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I used the System.out.println(decode); to check to see if the charecters matched the ones in the file and they do not. I can't figure out why, I have tried using a scanner and that throws it off more.
Data you have got is Base64 encoded. and you are not decoding it in your code. That is main reason behind other programs cannot read it as XML file.
Another is hidden in your Bytes of data. Start of Byte data is 77u/ which is saying data is BINARY data and becomes problem here.
Use Link to experience decoded data:
http://www.opinionatedgeek.com/dotnet/tools/base64decode/
If you will use 77u/ at start of data you will experience data is BINARY and will get downloaded as file. And if you do not use 77u/ it will show output online only.
Remove first 4 char while processing your data and then you are good to go inside java code only.
EDIT
Please use below code snippet. You are re-encoding byte array. You need to decode it. Also this process needs little bit conversions of String to Byte and vice-versa.
try {
File file = new File("C:\\Users\\ABC\\Desktop\\xml.txt");
InputStream myScan = new FileInputStream(file);
byte[] b = new byte[(int)file.length()];
myScan.read(b);
String cowo = new String(b);
System.out.println( cowo );
String decoded = new String(DatatypeConverter.parseBase64Binary(cowo));
String cat = b.toString();
System.out.println(decoded);
byte[] bArray = cat.getBytes();
OutputStream out = new FileOutputStream("C:\\Users\\ABC\\Desktop\\cow.xml");
out.write(decoded.getBytes());
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Read the bytes:
byte[] b;
try (InputStream in = new FileInputStream(file)) {
b = new byte[(int) file.length()];
in.read(b);
} // Closes in
Which in Java 7 goes easier:
b = Files.readAllBytes(file.toPath());
or immediately with Path i.o. Fiile:
Path path = Paths.get("C:\\Users\\khurt\\Desktop\\xml.txt");
b = Files.readAllBytes(path);
As Base64 only uses ASCII do:
String encoded = new String(b, StandardCharsets.US_ASCII);
Parse Base64 text to byte[]
b = DatatypeConverter.parseBase64Binary(encoded);
If you want the XML as text:
String decoded = new String(b, StandardCharsets.UTF_8);
By the way, the XML starts with "\ufeff" the Unicode BOM character, which is redundand.
Addendum 2021-11-16
Nowadays there is one Base64 class in java SE:
b = Base64.getDecoder().decode(b);
or even (suitable for large files):
b = Base64.getDecoder().decode(Files.newInputStream(path));
I used ostermillerutils library to create base64 string but I get OutOfMemory error if the image is heavy. If the image I try to convert is a simple image, the code is working fine.
public String createBase64String(InputStream in) {
//collect = new ByteArrayOutputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for(int readNum; (readNum = in.read(buf)) != -1; ) {
bos.write(buf, 0, readNum);
}
}
catch (IOException ex) {
Logger.getInstance().debug("XML createBase64String: IOException");
return null;
}
finally {
if (in != null) {
try {
in.close();
}
catch (IOException ex) {
;
}
}
}
byte[] ba = bos.toByteArray();
String coded = Base64.encodeToString(ba);
return coded;
}
I also tried doing this but the base64 was incorrect when I tried to decode it.
public void createBase64String(InputStream in) throws IOException {
//collect = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int readNum = 0;
try {
while((readNum = in.read(buf)) != -1)
{
smtp.addBase64(Base64.encodeBase64String(buf));
}
}
catch (IOException ex) {
Logger.getInstance().debug("XML createBase64String: IOException");
}
finally {
if (in != null) {
in.close();
}
}
}
Please suggest solutions for JDK 1.4 and also for later versions of Java.
If you like to write the encoded content straight into a file then use the following code
public void encode(File file, OutputStream base64OutputStream) {
InputStream is = new FileInputStream(file);
OutputStream out = new Base64OutputStream(base64OutputStream)
IOUtils.copy(is, out);
is.close();
out.close();
}
IOUtils class from Apache Commons IO.
EDIT
Since you want to do it using BufferedWriter, use it as follows
OutputStream out = Base64OutputStream(smtpSocket.getOutputStream());
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
IOUtils.copy(is, bw);
It sounds like the problem is that you're having to manipulate too much data in memory when you read the entire image. One fix would be to increase the Java heap size until you have enough memory, but that would just be avoiding the problem rather than solving it.
A better option would be to look at a streaming implementation of a Base64 encoder. This would mean you're only working on a subset of the image at any time. I believe that Base64OutputStream from Apache Commons would do the job for you.
I've fixed my problem by using javabase64-1.3.1.jar library.
OutputStream fos2 = FileUtil.getOutputStream(base64FileName, FileUtil.HDD);
InputStream in2 = FileUtil.getInputStream(fileName, FileUtil.HDD);
Base64.encode(in2, fos2);
in2.close();
fos2.close();
I stored the base64 string to a text file first.
public void createBase64String(InputStream in) throws IOException {
baos = new ByteArrayOutputStream();
byte[] buf = new byte[BUFFER_SIZE];
int readNum = 0;
smtp.addBase64("\t\t");
try {
while ((readNum = in.read(buf)) >= 0) {
baos.write(buf, 0, readNum);
smtp.addBase64(baos.toString());
baos.reset();
}
}
catch (IOException ex) {
LogUtil.error("Sending of Base64 String to SMTP: IOException: " + ex);
}
finally {
if (in != null) {
in.close();
baos.close();
}
}
baos = null;
buf = null;
}
then send each line to smtp's socket outputstream.
From Java 8 onwards, there is a simple way to implement base64 encoding in an output stream with one line of code and no external dependencies:
import java.util.Base64;
OutputStream os = ...
OutputStream base64 = Base64.getEncoder().wrap(os);
Base64 also provides other flavors of base64 encoder; see javadocs:
Base64
Base64.Encoder.wrap