Java-IO流每日一考
1.说明流的三种分类方式
字节流,字符流
节点流,处理流
输入流,输出流
流向:输入流、输出流
数据单位:字节流、字符流
流的角色:节点流、处理流
2. 写出4个IO流中的抽象基类,4个文件流,4个缓冲流
4个抽象基类:InputStream、OutputStream、Reader、Writer
4个文件流:FileInputStream...
4个缓冲流:BufferInputStream...
3.字节流与字符流的区别与使用情境
字节流的read方法形参传入的是一个byte数组,用于传输图片、视频等非文本文件
字符流的read方法形参传入的是一个char数组,用于传输文本文件
4.使用缓冲流实现a.jpg文件复制为b.jpg文件的操作
1 package www.exer.collection; 2 3 import java.io.*; 4 5 public class IObufferTest { 6 public static void main(String[] args) { 7 long start = System.currentTimeMillis(); 8 BufferedInputStream ips = null; 9 BufferedOutputStream ios = null; 10 try { 11 File srcfile = new File("D:\\整理\\Exer_code\\src\\www\\test1.jpg"); 12 File destfile = new File("D:\\整理\\Exer_code\\src\\www\\test2.jpg"); 13 14 FileInputStream fis = new FileInputStream(srcfile); 15 FileOutputStream fos = new FileOutputStream(destfile); 16 17 ips = new BufferedInputStream(fis); 18 ios = new BufferedOutputStream(fos); 19 20 byte[] buffer = new byte[10]; 21 int len; 22 while ((len=ips.read(buffer)) != -1){ 23 ios.write(buffer,0,len); 24 } 25 } catch (IOException e) { 26 e.printStackTrace(); 27 } finally { 28 29 30 try { 31 if(ips != null) 32 ips.close(); 33 } catch (IOException e) { 34 e.printStackTrace(); 35 } 36 try { 37 if(ios != null) 38 ios.close(); 39 } catch (IOException e) { 40 e.printStackTrace(); 41 } 42 } 43 long end = System.currentTimeMillis(); 44 System.out.println("复制完成,用时:"+(end - start)); 45 } 46 }
11-18行可用创建匿名对象的方式:
package www.exer.collection; import java.io.*; public class IObufferTest { public static void main(String[] args) { long start = System.currentTimeMillis(); BufferedInputStream ips = null; BufferedOutputStream ios = null; try { ips = new BufferedInputStream(new FileInputStream(new File("D:\\整理\\Exer_code\\src\\www\\test1.jpg"))); ios = new BufferedOutputStream(new FileOutputStream(new File("D:\\整理\\Exer_code\\src\\www\\test2.jpg"))); byte[] buffer = new byte[10]; int len; while ((len=ips.read(buffer)) != -1){ ios.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { try { if(ips != null) ips.close(); } catch (IOException e) { e.printStackTrace(); } try { if(ios != null) ios.close(); } catch (IOException e) { e.printStackTrace(); } } long end = System.currentTimeMillis(); System.out.println("复制完成,用时:"+(end - start)); } }
5.转换流是哪两个类,分别的作用是什么?请分别创建两个类的对象。
InputStreamReader:将输入的字节流转换为输入的字符流。 解码
OutputStreamWriter:将输出的字符流转换为输出的字节流。编码
InputStreamReader isr = new InputStreamReader(new FileInputStream(“a.txt”),”utf-8”);
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(“b.txt”),”gbk”);