File和byte[]转换
2017-12-26 09:59
183 查看
public static byte[] FileToByte(String filePath)
{
byte[] buffer = null;
try
{
File file = new File(filePath);
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();
bos.close();
buffer = bos.toByteArray();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return buffer;
}
public static void FileToByte(byte[] buf, 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 + File.separator + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(buf);
}
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();
}
}
}
}
{
byte[] buffer = null;
try
{
File file = new File(filePath);
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();
bos.close();
buffer = bos.toByteArray();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return buffer;
}
public static void FileToByte(byte[] buf, 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 + File.separator + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(buf);
}
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();
}
}
}
}
相关文章推荐
- File 对象实例与Byte[]之间的转换
- Java中File,byte[],Object间的转换
- 字节流转换为字符串(byteToString byteToFile)
- Java中File,byte[],Object间的转换
- java File和Byte[]数组 相互转换
- 转转转--Java File和byte数据之间的转换
- C#图像处理:Stream 与 byte[] 相互转换,byte[]与string,Stream 与 File 相互转换等
- 【转载】java输入流转为文件 InputStreamToFile 以及 byte[]和InputStream的相互转换
- File和byte[]转换
- Java File和byte数据之间的转换
- Java File,object,byte[]间转换
- java中File,byte[],Object间的转换
- File和byte[]转换
- JAVA 把File文件转换成Byte[]数组的标准写法
- File,FileStream,byte[]3者互相转换总结(转)
- File,FileStream,byte[]3者互相转换总结
- Java中File,byte[],Object间的转换
- java 中 byte[]、File、InputStream 互相转换
- 【java】java 中 byte[]、File、InputStream 互相转换
- File,FileStream,byte[]3者互相转换总结(转)