文件拷贝-代码
文件拷贝的基本代码:
public class ByteStreamDemo03 {public static void main(String[] args) throws IOException {//创建对象FileInputStream fis = new FileInputStream("D:\\itheima\\movie.mp4");FileOutputStream fos = new FileOutputStream("copy.mp4");//拷贝//核心思想:边读边写int b;while ((b= fis.read()) != -1){fos.write(b);}//先开的后释放fos.close();fis.close();}}
文件拷贝的弊端和解决方法:
弊端:一次读取一个字节
解决方法:一次读取多个字节
public class ByteStreamDemo04 {public static void main(String[] args) throws IOException {/*public int read(byte[] buffer) 一次读一个字节数组数据*/FileInputStream fis = new FileInputStream("a.txt");byte[] bytes = new byte[2];int len1 = fis.read(bytes);System.out.println(len1);String str1 = new String(bytes,0,len1);System.out.println(str1);int len2 = fis.read(bytes);System.out.println(len2);String str2 = new String(bytes,0,len2);System.out.println(str2);int len3 = fis.read(bytes);System.out.println(len3);String str3 = new String(bytes,0,len3);System.out.println(str3);fis.close();} }
拷贝改写(一次读多个字节):
public class ByteStreamDemo05 {public static void main(String[] args) throws IOException {long start = System.currentTimeMillis();FileInputStream fis = new FileInputStream("D:\\itheima\\movie.mp4");FileOutputStream fos = new FileOutputStream("copy2.mp4");int len;byte[] bytes = new byte[1024 * 1024 * 5];while ((len = fis.read(bytes)) != -1){fos.write(bytes,0,len);}fos.close();fis.close();long end= System.currentTimeMillis();System.out.println(end - start);} }