1.文件转byte数组
a.传统方式:
//文件路径具体到文件名字
File fileOne = new File("/file/file.txt");
byte[] bytesArray = new byte[(int) fileOne .length()];
FileInputStream fis = new FileInputStream(fileOne );
//读取文件到byte[]
fis.read(bytesArray);
fis.close();
b.Nio方式:
String filePath = "/file/file.doc";
//方式一:
byte[] bytesArray= Files.readAllBytes(new File(filePath).toPath());
//方式二:
byte[] bytesArray= Files.readAllBytes(Paths.get(filePath));
2.char[]转换byte[]
//定义一个要转换的char数组
char[] charArray = new char[] { 'a', 'b', 'c', 'd', 'e'};
String str = new String(charArray );
byte[] byteArray = str.getBytes();
3.int,String,float转换byte[]
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
try {
// int转换byte数组
dos.writeLong(66);
//Char
dos.writeChar('1');
//float
dos.writeFloat(1.01f);
//String
dos.writeUTF("文件");
} catch (IOException e) {
e.printStackTrace();
}
//写进byte[]
byte[] byteArray = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
DataInputStream dis = new DataInputStream(bais);