Write a Java Program to Convert File to byte array and Vice-Versa

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Convert File to byte array and Vice-Versa
Java Program to Convert File to byte array and Vice-Versa

Write a Java Program to Convert File to byte array and Vice-Versa

PROGRAM: Java Program to Convert File to byte array and Vice-Versa

/*Java Program to Convert File to byte array and Vice-Versa*/

1: Convert File to byte[]

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) {

}
}
}

2: Convert byte[] to File

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) {

}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *