欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 文件和byte互转的实例

程序员文章站 2023-12-18 20:21:34
实例如下所示: /** * 获得指定文件的byte数组 */ private byte[] getbytes(string filepath...

实例如下所示:

/** 
  * 获得指定文件的byte数组 
  */ 
 private byte[] getbytes(string filepath){ 
  byte[] buffer = null; 
  try { 
   file file = new file(filepath); 
   fileinputstream fis = new fileinputstream(file); 
   bytearrayoutputstream bos = new bytearrayoutputstream(1000); 
   byte[] b = new byte[1000]; 
   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; 
 }
 
 /** 
  * 根据byte数组,生成文件 
  */ 
 public static void getfile(byte[] bfile, 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(bfile); 
  } catch (exception e) { 
   e.printstacktrace(); 
  } finally { 
   if (bos != null) { 
    try { 
     bos.close(); 
    } catch (ioexception e1) { 
     e1.printstacktrace(); 
    } 
   } 
   if (fos != null) { 
    try { 
     fos.close(); 
    } catch (ioexception e1) { 
     e1.printstacktrace(); 
    } 
   } 
  } 
 }

以上这篇java 文件和byte互转的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

上一篇:

下一篇: