java读取文件及文件流(转)

import java.io.BufferedInputStream;
import java.io.File;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class Util{

public Util() {
}

/**
   * 读取源文件内容
   * @param filename String 文件路径
   * @throws IOException
   * @return byte[] 文件内容
   */
public static byte[] readFile(String filename) throws IOException {

    File file =new File(filename);
    if(filename==null || filename.equals(""))
    {
      throw new NullPointerException("无效的文件路径");
    }
    long len = file.length();
    byte[] bytes = new byte[(int)len];

    BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream(file));
    int r = bufferedInputStream.read( bytes );
    if (r != len)
      throw new IOException("读取文件不正确");
    bufferedInputStream.close();

    return bytes;

}

/**
   * 将数据写入文件
   * @param data byte[]
   * @throws IOException
   */
public static void writeFile(byte[] data,String filename) throws IOException{
    File file =new File(filename);
    file.getParentFile().mkdirs();
    BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(new FileOutputStream(file));
    bufferedOutputStream.write(data);
    bufferedOutputStream.close();

}

/**
   * 从jar文件里读取class
   * @param filename String
   * @throws IOException
   * @return byte[]
   */
public byte[] readFileJar(String filename) throws IOException{
    BufferedInputStream bufferedInputStream=new BufferedInputStream(getClass().getResource(filename).openStream());
    int len=bufferedInputStream.available();
    byte[] bytes=new byte[len];
    int r=bufferedInputStream.read(bytes);
    if(len!=r)
    {
      bytes=null;
      throw new IOException("读取文件不正确");
    }
    bufferedInputStream.close();
    return bytes;
}

/**
   * 读取网络流,为了防止中文的问题,在读取过程中没有进行编码转换,而且采取了动态的byte[]的方式获得所有的byte返回
   * @param bufferedInputStream BufferedInputStream
   * @throws IOException
   * @return byte[]
   */
public byte[] readUrlStream(BufferedInputStream bufferedInputStream) throws IOException {
    byte[] bytes = new byte[100];
    byte[] bytecount=null;
    int n=0;
    int ilength=0;
    while((n=bufferedInputStream.read(bytes))>=0)
     {
      if(bytecount!=null)
        ilength=bytecount.length;
      byte[] tempbyte=new byte[ilength+n];
      if(bytecount!=null)
      {
        System.arraycopy(bytecount,0,tempbyte,0,ilength);
      }

      System.arraycopy(bytes,0,tempbyte,ilength,n);
      bytecount=tempbyte;

      if(n<bytes.length)
        break;
    }
    return bytecount;
 }

}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值