Algorithm


Convert File to Byte Array:

  1. Open File:

    • Accept the file path as input.
    • Open the file using FileInputStream.
  2. Allocate Memory:

    • Determine the size of the file.
    • Allocate a byte array with the size of the file.
  3. Read File Content:

    • Read the content of the file into the byte array using FileInputStream.read().
  4. Close File:

    • Close the FileInputStream.
  5. Use the Byte Array:

    • The byte array now contains the content of the file.

Convert Byte Array to File:

  1. Open Output File:

    • Accept the output file path as input.
    • Open the file using FileOutputStream.
  2. Write Byte Array:

    • Write the content of the byte array to the file using FileOutputStream.write().
  3. Close Output File:

    • Close the FileOutputStream.
  4. Use the Output File:

    • The file now contains the content of the byte array.

 

Code Examples

#1 Code Example- Java Programing Convert File to byte[]

Code - Java Programming

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;

public class FileByte {

    public static void main(String[] args) {

        String path = System.getProperty("user.dir") + "\\src\\test.txt";

        try {
            byte[] encoded = Files.readAllBytes(Paths.get(path));
            System.out.println(Arrays.toString(encoded));
        } catch (IOException e) {

        }
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
[84, 104, 105, 115, 32, 105, 115, 32, 97, 13, 10, 84, 101, 115, 116, 32, 102, 105, 108, 101, 46]

#2 Code Example- Java Programing Convert byte[] to File

Code - Java Programming

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ByteFile {

    public static void main(String[] args) {

        String path = System.getProperty("user.dir") + "\\src\\test.txt";
        String finalPath = System.getProperty("user.dir") + "\\src\\final.txt";

        try {
            byte[] encoded = Files.readAllBytes(Paths.get(path));
            Files.write(Paths.get(finalPath), encoded);
        } catch (IOException e) {

        }
    }
}
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Java Programing Example to Convert File to byte array and Vice-Versa-DevsEnv