Convert byte[] array to File using Java
Last Updated :
18 May, 2022
As we know whenever it comes to writing over a file, write() method of the File class comes into play but here we can not use it in order to convert that byte into a file. In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class.
Implementation: Convert a String into a byte array and write it in a file.
Example:
Java
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class GFG {
static String FILEPATH = "" ;
static File file = new File(FILEPATH);
static void writeByte( byte [] bytes)
{
try {
OutputStream os = new FileOutputStream(file);
os.write(bytes);
System.out.println( "Successfully"
+ " byte inserted" );
os.close();
}
catch (Exception e) {
System.out.println( "Exception: " + e);
}
}
public static void main(String args[])
{
String string = "GeeksForGeeks"
+ " - A Computer Science"
+ " Portal for geeks" ;
byte [] bytes = string.getBytes();
writeByte(bytes);
}
}
|
Output: On console
Successfully byte inserted
Now let us also discuss the use-case in order how to write Integer, Double, Character Values in the File (using Wrapper Class)
Example:
Java
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class GFG {
static String FILEPATH = "" ;
static File file = new File(FILEPATH);
static void writeByte( byte [] byteInt, byte [] byteChar,
byte [] byteDouble)
{
try {
OutputStream os = new FileOutputStream(file);
os.write(byteInt);
os.write(byteChar);
os.write(byteDouble);
System.out.println(
"Successfully byte inserted" );
os.close();
}
catch (Exception e) {
System.out.println( "Exception: " + e);
}
}
public static void main(String args[])
{
int num = 56 ;
char ch = 's' ;
double dec = 78.9 ;
byte [] byteInt = Integer.toString(num).getBytes();
byte [] byteChar = Character.toString(ch).getBytes();
byte [] byteDouble = Double.toString(dec).getBytes();
writeByte(byteInt, byteChar, byteDouble);
}
}
|
Output: On console
Successfully byte inserted
Share your thoughts in the comments
Please Login to comment...