Java丨【第九章】输入、输出系统

字节流

DataInputStream字节输入流

     读取数据的方法如下: 

abstract int read() throws IOException:读取一个字节数据,并返回读到的数据,若返回-1,表示读到了流的末尾。

 int read(byte[] b) throws IOException:从流中读取一定数量的字节,存储在缓冲区数组b中,并以整数形式返回实际读取的字节数,若返回-1,表示读到了流的末尾。

 int read(byte[] b, int off, int len) throws IOException:将数据读入一个字节数组,同时返回实际读取字节数,若返回-1,表示读到了流的末尾。 

long skip(long n) throws IOException:跳过(放弃)此流中的n个字节,返回跳过的字节数。若n为负,则不跳过任何字节。

int available() throws IOException:返回此流下一个方法调用可不受阻塞地从流中读取(或跳过)的估计字节数。

 void close():关闭流并释放与之相关的系统资源。

DataOutputStream表示字节输出流

        写入数据的方法如下:

 abstract void write(int b) throws IOException:将b的最低一个字节写入此流,高位字节(3个)丢弃。 

void write(byte[] b) throws IOException:将b.length个字节从指定的byte数组写入此流。

void write(byte[] b,int off,int len)throws IOException:将指定byte数组中从偏移量off开始的len个字节写入此流。

void flush()throws IOException:刷新此流并强制写出所有缓冲的输出字节。

 void close()throws IOException:关闭此流并释放与之相关的系统资源。

典例1:任意文件复制

public class CopyFile{
    public static void filecopy(String src,String dsc) throws Exception{
//src表示源文件,dsc表示目标文件

    DataInputStream dis=new DataInputStream(new FileInputStream(src));
    DataOutputStream dos=new DataOutputStream(new FileInputStream(drc));

    byte[] buf=new byte[4*1024*1024];//buf缓冲区,设置为4MB空间较大速度较快
    int n;
    while((n=dis.read(buf))!=-1)
//int read(byte[] b) throws IOException:从流中读取一定数量的字节,存储在缓冲区数组b中,并以整数形式返回实际读取的字节数,若返回-1,表示读到了流的末尾。
    {
      dos.write(buf,0,n);
//void write(byte[] b,int off,int len)throws IOException:将指定byte数组中从偏移量off开始的len个字节写入此流。

     }
    dis.close;
    dos.close;
   }
   public static void main(String[] args) throws Exception
   {
    filecopy("c:/abc.exe","d:/abc_1.exe");//引号内表示源文件与目标文件的根目录,用斜杠/表示
   }
}

典例2:文件的读写操作

1)在D:/data/dat中写入10个整数值(1-100之间随机)

2)从D:/data/dat中读出10个整数值,并在屏幕中输出(可进行进一步求和、平均值、最值等问题)

public static void main(String[] args) throws Exception
{ 
   DataOutputStream dos=new DataOutputStream(new FileOutputStream("D:/data.dat"));
   Random r=new Random();
   for (int i=1;i<=10;i++)
   {
      int v=r.nextInt(100)+1;//只是随机读了0-99之前的数所以还要再加一
      dos.write(v);
   }
  dos.close();
  
  DataInputStream dis=new DataInputStream(new FileInputStream("D:/data.dat"));
  for(int i=1;i<=10;i++)
  {
      int v=dis.readInt();//readInt()函数注意
      System.out.println(" "+v);
      dis.close();
  }
    
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值