创建文件,将byte数组写入文件
package sqy;
import org.junit.jupiter.api.Test;
import java.io.*;
import java.util.Arrays;
/**
* @author suqinyi
* @Date 2021/7/1
*/
public class FileCreateTest {
/**
* 创建文件
* @throws Exception
*/
@Test
public void test01() throws Exception {
//1、文件路径
String filePath = "D:/abc.zip";
File sourceFile = new File(filePath);
//2、创建文件
if (!sourceFile.getParentFile().exists()) {
sourceFile.getParentFile().mkdirs();
System.out.println("创建成功");
}
//3、获取文件的byte数组 byte[] bufs
byte[] bufs = {80, 75, 3, 4, 20, 0, 8, 8, 8, 0, 75, -122, -31, 82, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 115, 113, 121, -30, -128, -108, 116, 101, 115, 116, 46, 120, 109, 108, -77, -79, -81, -56, -51, 81, 40, 75, 45, 42, -50, -52, -49, -77, 85, 50, -44, 51, 80, 82, 72, -51, 75, -50, 79, -55, -52, 75, -73, 85, 10, 13, 113, -45, -75, 80, -78, -73, -77, -55, 73, 45, 75, -51, -15, -49, 75, -75, -29, -27, -126, -80, 67, -54, -13, 17, -20, -116, -94, -44, 84, 67, 32, -80, 51, 126, -66, 107, -7, -117, -82, -90, -25, 77, 59, -97, -20, 104, -80, -47, 71, -109, 69, 81, 111, 4, 4, -56, -22, 119, -11, 32, -85, 7, -53, 2, -43, -21, 35, 91, -90, -113, -28, 10, 0, 80, 75, 7, 8, 109, 98, 55, 93, 105, 0, 0, 0, -72, 0, 0, 0, 80, 75, 1, 2, 20, 0, 20, 0, 8, 8, 8, 0, 75, -122, -31, 82, 109, 98, 55, 93, 105, 0, 0, 0, -72, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 115, 113, 121, -30, -128, -108, 116, 101, 115, 116, 46, 120, 109, 108, 80, 75, 5, 6, 0, 0, 0, 0, 1, 0, 1, 0, 60, 0, 0, 0, -91, 0, 0, 0, 0, 0};
//4、二进制数据写文件
this.byteArrayToFile(bufs, filePath);
}
/**
* 将byte写进文件
*/
public static void byteArrayToFile ( byte[] bytes, String filePath) throws Exception {
InputStream in = new ByteArrayInputStream(bytes);
File destFile = new File(filePath);
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
destFile.createNewFile();
OutputStream out = new FileOutputStream(destFile);
byte[] cache = new byte[1024];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
}
}
效果:
读取本地文件,转成byte数组
package sqy;
import org.junit.jupiter.api.Test;
import java.io.*;
import java.util.Arrays;
/**
* @author suqinyi
* @Date 2021/7/1
*/
public class FileCreateTest {
/**
* 读取本地文件转成byte数组
*/
@Test
public void test02() throws Exception {
//将本地文件读取成byte数组
byte[] fileByte = this.fileToByte("D:/abc.zip");
System.out.println("字节:"+Arrays.toString(fileByte));
}
/**
* 文件转换为二进制数组
*/
public static byte[] fileToByte(String filePath) throws Exception {
byte[] data = new byte[0];
File file = new File(filePath);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
byte[] cache = new byte[1024];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
data = out.toByteArray();
}
return data;
}
}
效果: