Algorithm
Convert File to Byte Array:
-
Open File:
- Accept the file path as input.
- Open the file using FileInputStream.
-
Allocate Memory:
- Determine the size of the file.
- Allocate a byte array with the size of the file.
-
Read File Content:
- Read the content of the file into the byte array using FileInputStream.read().
-
Close File:
- Close the FileInputStream.
-
Use the Byte Array:
- The byte array now contains the content of the file.
Convert Byte Array to File:
-
Open Output File:
- Accept the output file path as input.
- Open the file using FileOutputStream.
-
Write Byte Array:
- Write the content of the byte array to the file using FileOutputStream.write().
-
Close Output File:
- Close the FileOutputStream.
-
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
[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
Demonstration
Java Programing Example to Convert File to byte array and Vice-Versa-DevsEnv