文件转Byte[]、以及byte[]转文件的工具类
一、
1.文件转Byte[]:
// 第1步、使用File类找到一个文件
File f= new File("e:/demo/demoNext" + File.separator + "java.docx") ; // 声明File对象
// 第2步、通过子类实例化父类对象
InputStream input = null ; // 准备好一个输入的对象
input = new FileInputStream(f) ; // 通过对象多态性,进行实例化
// 第3步、进行读操作
byte result[] = new byte[1024] ; // 所有的内容都读到此数组之中
input.read(result) ; // 读取内容 网络编程中 read 方法会阻塞
// 第4步、关闭输出流
input.close() ; // 关闭输出流
System.out.println("内容为:" + result);
2.文件转Byte[]的工具类:
public class fileUtil {
//将文件转换成Byte数组
public static byte[] getBytesByFile(String pathStr) {
File file = new File(pathStr);
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
byte[] data = bos.toByteArray();
bos.close();
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
测试类调用:
String pathStr="e:/demo/demoNext/java.docx";
System.out.println("文件转byte:"+fileUtil.getBytesByFile(pathStr));
二、byte[]转文件的工具类:
public class fileUtil {
//将Byte数组转换成文件
public static void getFileByBytes(byte[] bytes, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
dir.mkdirs();
}
file = new File(filePath + "\\" + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
测试类调用:
//要生成文件的路径
String filePath="e:/demo";
//要生成文件的名字
String fileName="java.docx";
//result:byte[]
fileUtil.getFileByBytes(result, filePath, fileName);
还没有评论,来说两句吧...