IO实现文件COPY

1)

public class CopyFile {

public static void main(String[] args) throws IOException {
  FileInputStream fis = null;
  FileOutputStream fos = null;
  try {
   fis = new FileInputStream("src.txt");                   // 创建输入流, 关联file.txt
   fos = new FileOutputStream("dest.txt");            // 创建输出流, 关联dest.txt
   int b;                                                                  // 创建变量, 用来接收字节数据
   while ((b = fis.read()) != -1)                              // 使用输入流循环读取数据, 如果不是文件末尾
    fos.write(b);                                                    // 写出到输出流中
  } finally {
   try {
    if (fis != null)
     fis.close();                                                     // 关闭输入流
   } finally {
    if (fos != null)
     fos.close();                                                  // 关闭输出流
   }
  }
}

}

2)

public class CopyByArrayDemo {

public static void main(String[] args) throws IOException {
  FileInputStream fis = new FileInputStream("小情歌.mp3");
  FileOutputStream fos = new FileOutputStream("dest小情歌.mp3");
 
  byte[] buffer = new byte[1024];                     // 定义数组用来当作缓冲区, 越大越快, 但是更占内存
  int len;                                                          // 定义变量, 用来记住每次拷贝的个数
  while ((len = fis.read(buffer)) != -1)            // 从流中读取数据到buffer中, len记住读取了多少个
   fos.write(buffer, 0, len);                           // 将buffer中的数据写出, 写出len个
 
  fis.close();
  fos.close();
}

}

3)

public class CopyByBufferedDemo {

public static void main(String[] args) throws IOException {
  BufferedInputStream bis = new BufferedInputStream(new FileInputStream("src.txt"));
  BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("dest.txt"));
 
  int b;
  while ((b = bis.read()) != -1)            // 使用BufferedInputStream读一个, 其实内部已经读了一批, 放在了缓冲区中. 以后就不读文件了
   bos.write(b);                                  // 使用BufferedOutputStream写一个, 其实写到了内部缓冲区中, 缓冲区写满或者关流时才写到文件
 
  bis.close();
  bos.close();
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值