------http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
/** * @param args * IO流按流向分:输入流和输出流 * 按照操作的数据分:字节流和字符流 * 字节流的抽象基类,可以操作的是任意类型的数据 * InputStream * OutputStream * 字符流,可以操作的是纯文本的数据,获取的字节,将字节转换为字符,写出的时候,先写出的是字符,然后转换成字节 * Reader * Writer * 字节输入流 * FileInputStream读取一个文件,文件必须存在,如果不在,会抛出FileNotFoundException * 读取文件为什么返回是int而不是byte * 字节输出流 * FileOutputStream写出文件时,文件不用必须存在(路径存在),如果不存在就创建一个文件出来,如果想续写,用构造方法 * 在第二个参数传一个true * 四种拷贝: * 1,逐个字节拷贝(效率太低) * 2,定义一个大数组,文件多少个字节,数组就多大(容易内存溢出) * 3,定义一个小数组,是1024的整数倍 * 4,带Buffer的拷贝 * 两种异常处理方式 * 1,1.7版本以前的 * 2,1.7版本的 * @throws IOException * @throws IOException */ public static void main(String[] args) throws IOException { //demo1(); //demo2(); //demo3(); //demo4(); //demo5(); try( FileInputStream fis = new FileInputStream("a.txt"); FileOutputStream fos = new FileOutputStream("b.txt"); ){ int b; while((b = fis.read()) != -1) { fos.write(b); } } } public static void demo5() throws FileNotFoundException, IOException { FileInputStream fis = null; //局部变量在使用之前必须赋值 FileOutputStream fos = null; try { fis = new FileInputStream("a.txt"); fos = new FileOutputStream("b.txt"); int b; while((b = fis.read()) != -1) { fos.write(b); } } finally { try { if(fis != null) fis.close(); } finally { if(fos != null) fos.close(); } } } public static void demo4() throws FileNotFoundException, IOException { FileInputStream fis = new FileInputStream("a.txt"); FileOutputStream fos = new FileOutputStream("b.txt"); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(fos); int b; while((b = bis.read()) != -1) { bos.write(b); } bis.close(); bos.close(); } public static void demo3() throws FileNotFoundException, IOException { FileInputStream fis = new FileInputStream("a.txt"); FileOutputStream fos = new FileOutputStream("b.txt"); byte[] arr = new byte[8192]; int len; while((len = fis.read(arr)) != -1) { fos.write(arr,0,len); } fis.close(); fos.close(); } public static void demo2() throws FileNotFoundException, IOException { FileInputStream fis = new FileInputStream("a.txt"); FileOutputStream fos = new FileOutputStream("b.txt"); byte[] arr = new byte[fis.available()]; fis.read(arr); fos.write(arr); fis.close(); fos.close(); } public static void demo1() throws FileNotFoundException, IOException { FileInputStream fis = new FileInputStream("a.txt"); FileOutputStream fos = new FileOutputStream("b.txt"); int b; while((b = fis.read()) != -1) { fos.write(b); } fis.close(); fos.close(); } } |