Convert byte[] array to File using Java


The file class is a representation of directory path name in Java with different formats on different platforms. The file class contains the method of different path name which is responsible for deleting and renaming files by using the new directories. It is an abstract class in a string formation which can be either absolute or relative.

Algorithm to of Convert Byte[ ] Array to File

In this possible algorithm, we are going to show you how to perform a conversion process on a byte() array node to make it a file. By using this algorithm, we are going to build some Java syntax to get a broad view of the problem statement.

  • Step 1 − Start the process.

  • Step 2 − Declare and import the Java packages.

  • Step 3 − Declare a public class.

  • Step 4 − Declare a method which convert a byte array into Writer Class.

  • Step 5 − Declare a static byte type.

  • Step 6 − Declare a file writer class.

  • Step 7 − Declare a Call append() method.

  • Step 8 − Costruct a driver code.

  • Step 9 − Declare the various values.

  • Step 10 − Call the main method.

  • Step 11 − Get the return value as a file.

  • Step 12 − Terminate the process.

Syntax to Convert Byte[ ] Array to File

In this possible algorithm, we are going to show you how to perform a conversion process on a byte() array node to make it a file. By using this algorithm, we are going to build some Java syntax to get a broad view of the problem statement.

  • Step 1 − Start the process.

  • Step 2 − Declare and import the Java packages.

  • Step 3 − Declare a public class.

  • Step 4 − Declare a method which convert a byte array into Writer Class.

  • Step 5 − Declare a static byte type.

  • Step 6 − Declare a file writer class.

  • Step 7 − Declare a Call append() method.

  • Step 8 − Costruct a driver code.

  • Step 9 − Declare the various values.

  • Step 10 − Call the main method.

  • Step 11 − Get the return value as a file.

  • Step 12 − Terminate the process.

Syntax to Convert Byte[ ] Array to File

FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)
try (FileOutputStream fos = new FileOutputStream("pathname")) {
   fos.write(myByteArray);
}
try (FileOutputStream fos = new FileOutputStream("fullPathToFile")) {
   fos.write(byteArray);
} catch (IOException ioe) {
   ioe.printStackTrace();
}
String fileName = "file.test";
BufferedOutputStream bs = null;
try {
   Convert byte[] array to File using Java
   FileOutputStream fs = new FileOutputStream(new File(fileName));
   bs = new BufferedOutputStream(fs);
   bs.write(byte_array);
   bs.close();
   bs = null;
} catch (Exception e) {
   e.printStackTrace()
}
if (bs != null) try { bs.close(); } catch (Exception e) {}
File f = new File(fileName);
byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
try {
   Files.write(path, fileContent);
} catch (IOException ex) {
   Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}
Path path = Paths.get(p);
byte[] data = null;
try {
   data = Files.readAllBytes(path);
} catch (IOException ex) {
   Logger.getLogger(Agent1.class.getName()).log(Level.SEVERE, null, ex);
}
File f = new File(fileName);
byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
try {
   Files.write(path, fileContent);
} catch (IOException ex) {
   Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}

In this possible syntax above, we have tried to show you how to perform a conversion process on a byte() node to make it a file. With these syntax we are heading towards to build some Java codes to solve the problem statement in an efficient manner.

Approaches to Follow

  • Approach 1 − Java Program to convert Byte Array to File by using java.io.FileOutputStream to define exceptions related to the process and use of writeByte(byteInt, byteChar, byteDouble) and writer and Call append() method

  • Approach 2 − Java Program to convert Byte Array to File by using java.io.ByteArrayInputStream and the sub-class of InputStream method

Approach 1

Use of Java.io.FileOutputStream to Define Exceptions Related to the Process and Implement WriteByte(ByteInt, ByteChar, byteDouble) and Writer and Call Append() Method

Use of Java.io.FileOutputStream and Exception Method

In this possible approach, we are going to apply the java.io.FileOutputStream method on an byte[] array list. By following this approach we will run a conversion on that byte array list to convert it into a file by defining an exception.

File outputFile = tempFolder.newFile("FILE NAME");
try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
   outputStream.write(dataForWriting);
}
public static void main(String[] args) throws IOException {
byte[] bytes = "frontbackend.com".getBytes(StandardCharsets.UTF_8);
try (FileOutputStream fos = new FileOutputStream("FILE PATH")) {
fos.write(bytes);

Example

//Java Program to convert Byte Array to File by using java.io.FileOutputStream to define exceptions related to the process
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class ARBRDD{
   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" + "the byte has been inserted");
         os.close();
      }
      catch (Exception e){
         System.out.println("Exception Is Here: " + e);
      }
   }
   public static void main(String args[]){
      String string = "TutorialsPoint" + " -Is A Computer Science" + "Data Source Portal For Coding Minds";
      byte[] bytes = string.getBytes();
      writeByte(bytes);
   }
}

Output

Exception Is Here: java.io.FileNotFoundException: (No such file or directory)

Use of Multipale Methods With WriteByte(ByteInt, ByteChar, ByteDouble) Method

In this possible approach, we are going to apply the multipale methods with writeByte(byteInt, byteChar, byteDouble) method on an byte[] array list. By following this approach we will run a conversion on that byte array list to convert it into a file by defining an exception.

Example

// Java Program to Convert Integer, Character and Double types into Bytes and Writing it in a File by using multipale methods with writeByte(byteInt, byteChar, byteDouble)
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class ARBRDD{
   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 the byte has been inserted");
         os.close();
      }
      catch (Exception e) {
         System.out.println("Exception is here. Note it down: " + 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

Exception is here. Note it down:
java.io.FileNotFoundException: (No such file or directory)

Use of Writer and Call Append() Method Method

In this possible approach, we are going to apply the multipale methods with writer and Call append() method on an byte[] array list. By following this approach we will run a conversion on that byte array list to convert it into a file.

Example

//Java Program Convert byte() array list to a file by using a writer and Call append() method
import java.io.StringWriter;
import java.io.Writer;
public class ARBRDD{
   static String writeByte(byte[] byteString,
   byte[] byteInt,
   byte[] byteChar,
   byte[] byteDouble){
      Writer writer = new StringWriter();
      try {
         writer
         .append(new String(byteString)
         + new String(byteDouble)
         + new String(byteChar)
         + new String(byteInt));
         writer.close();
      }
      catch (Exception e) {
         System.out.println("Exception Is Here: " + e);
      }
      return writer.toString();
   }
   public static void main(String args[]){
      String str = "Speed of the light is: ";
      int num = 7;
      char ch = 'e';
      double dec = 16.0;
      // Insert String value
      byte[] byteString = str.getBytes();
      // Insert int value
      byte[] byteInt = Integer.toString(num).getBytes();
      // Insert char value
      byte[] byteChar = Character.toString(ch).getBytes();
      // Insert double value
      byte[] byteDouble = Double.toString(dec).getBytes();
      // Call the method
      System.out.println(writeByte(byteString, byteInt,
      byteChar,
      byteDouble));
   }
}

Output

Speed of the light is: 16.0e7

Approach 2

Using Java.io.ByteArrayInputStream and the Sub-class of InputStream Method.

Use of the Java.io.ByteArrayInputStream Method

In this possible approach, we are going to apply the multipale methods with java.io.ByteArrayInputStream method on an byte[] array list. By following this approach we will run a conversion on that byte array list to convert it into a file.

BufferedImage bImage = ImageIO.read(new File("FILE NAME"));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bImage, "FILE TYPE", bos );
byte [] data = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(data);
BufferedImage bImage2 = ImageIO.read(bis);
ImageIO.write(bImage2, "FILE TYPE", new File("OUTPUT FILE") );
System.out.println("OUTPUT STATEMENT");

Example

//Java Program Convert byte() array list to a file by using a java.io.ByteArrayInputStream method
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
public class ARBRDD{
   public static void main(String a[]){
      String str = "Converting to input stream byte[] array to file";
      byte[] content = str.getBytes();
      int size = content.length;
      InputStream is = null;
      byte[] b = new byte[size];
      try {
         is = new ByteArrayInputStream(content);
         is.read(b);
         System.out.println("Operation Completed: "+new String(b));
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         try{
            if(is != null) is.close();
         } catch (Exception ex){
         }
      }
   }
}

Output

Operation Completed: Converting to input stream byte[] array to file

Use of the Sub-class of InputStream Method

In this possible approach, we are going to apply the multipale methods with sub class of InputStream method on an byte[] array list. By following this approach we will run a conversion on that byte array list to convert it into a file.

Example

//Java program to create InputStream from byte array ByteArrayInputStream is sub-class of InputStream
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class ARBRDD{
   public static void main(String args[]) {
      String str = "I AM AN INDIAN";
      byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
      InputStream is = new ByteArrayInputStream(bytes);
      String stringFromBytes = streamToString(is, StandardCharsets.UTF_8);
      System.out.println("File recreated from bytes is: " + str);
      OutputStream os = new ByteArrayOutputStream();
      try {
         os.write(bytes);
         os.close();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
   public static String streamToString(InputStream is, Charset encoding) {
      BufferedReader br
      = new BufferedReader(new InputStreamReader(is, encoding));
      StringBuilder sb = new StringBuilder(1024);
      try {
         String line = br.readLine();
         while (line != null) {
            sb.append(line);
            line = br.readLine();
         }
      } catch (IOException io) {
         System.out.println("Failed to read from the File");
         io.printStackTrace();
      } finally {
         try {
            br.close();
         } catch (IOException ioex) {
            System.out.println("Failed to close the Files");
            ioex.printStackTrace();
         }
      }
      return sb.toString();
   }
}

Output

File recreated from bytes is: I AM AN INDIAN

Conclusion

In a Java environment, the writer class used for to write a character stream to pass an argument related to the byte array. Today in this article, we have learned about the various methods how to convert the particular byte[] array list to a specific file in a Java environment. By using the above mentioned syntax and algorithm we have built some Java codes to explain the problem statement in an efficient manner.

Updated on: 19-Jan-2024

75 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements