概述
File与byte数组和inputstream相互转换
package com.sk.Util;
/**
* *sk
*/
import java.io.*;
import java.nio.channels.FileChannel;
public class fileUtils {
/**
* *byte数组转inputstream
* @param bytes
* @return
*/
public static InputStream bytesToInputStream(byte[] bytes) {
InputStream inputStream = new ByteArrayInputStream(bytes);
return inputStream;
}
/**
* *inputstream转byte数组
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] inputStreamToBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = inputStream.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
/**
* *inputstream转file
* @param inputStream
* @param filePath
* @param fileName
* @throws IOException
*/
public static void inputStreamToFile(InputStream inputStream, String filePath, String fileName) throws IOException {
File dir = new File(filePath);
if (!dir.exists()) {// 判断文件目录是否存在
dir.mkdirs();
}
File file = new File(filePath + "//" + fileName);
FileOutputStream outStream = new FileOutputStream(file);
FileChannel in = ((FileInputStream) inputStream).getChannel();
FileChannel out = outStream.getChannel();
in.transferTo(0, in.size(), out);
}
/**
* *file转inputstream
* @param file
* @return
* @throws FileNotFoundException
*/
public static InputStream fileToInputStream(File file) throws FileNotFoundException {
InputStream is = new FileInputStream(file);
return is;
}
/**
* *byte数组转file
* @param bytes
* @param filePath
* @param fileName
* @throws IOException
*/
public static void bytesToFile(byte[] bytes, String filePath, String fileName) throws IOException {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
File dir = new File(filePath);
if (!dir.exists()) {// 判断文件目录是否存在
dir.mkdirs();
}
file = new File(filePath + "//" + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
bos.close();
fos.close();
}
/**
* *file转byte数组
* @param file
* @return
* @throws IOException
*/
public static byte[] fileToBytes(File file) throws IOException {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
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;
}
/**
* *删除文件目录
* @param dir
*/
public static void deleFiletDir(String dir) {
File file = new File(dir);
if (file.isDirectory()) {
delFile(file);
}
}
private static void delFile(File file) {
File[] files = file.listFiles();
if (files != null && files.length != 0) {
for (int i = 0; i < files.length; i++) {
delFile(files[i]);
}
}
file.delete();
}
}
最后
以上就是野性面包为你收集整理的File与byte数组和inputstream相互转换的全部内容,希望文章能够帮你解决File与byte数组和inputstream相互转换所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复