byte[] to file in Java
To write a byte[]
to a file in Java, you can use the following code:
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
byte[] bytes = {1, 2, 3};
try (FileOutputStream fos = new FileOutputStream("file.txt")) {
fos.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
This code creates a FileOutputStream
that writes to the file file.txt
. It then writes the contents of the bytes
array to the file using the write()
method of the FileOutputStream
.
Alternatively, you can also use the Files
class from the java.nio.file
package to write the byte[]
to a file:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) {
byte[] bytes = {1, 2, 3};
try {
Files.write(Paths.get("file.txt"), bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
This code writes the bytes
array to the file file.txt
using the write()
method of the Files
class.