Below snippet writes the byte array to a file.
public static void writeToFile(byte[] dataToWrite, String outputFilePath) throws IOException {
File outputFile = new File(outputFilePath);
if (outputFile.getParentFile() != null) {
outputFile.getParentFile().mkdirs();
}
try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
fos.write(dataToWrite);
}
}
Find the below working application.
WriteByteArrayToAFile.java
package com.sample.app;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteByteArrayToAFile {
public static void writeToFile(byte[] dataToWrite, String outputFilePath) throws IOException {
File outputFile = new File(outputFilePath);
if (outputFile.getParentFile() != null) {
outputFile.getParentFile().mkdirs();
}
try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
fos.write(dataToWrite);
}
}
public static void main(String[] args) throws IOException {
String str = "Hello World";
byte[] bytes = str.getBytes();
writeToFile(bytes, "/Users/Shared/demo1/demo2/a.txt");
}
}
You may like
Get file name from absolute path
Count number of lines in a file
Download file from Internet using Java
No comments:
Post a Comment