------- android培训、java培训、期待与您交流! ----------
- /*
- IO流之字节流的两个基类:
- InputStream OutputStream
- 字节流的缓冲区
- BufferedInputStream BufferedOutputStream
- */
- import java.io.*;
- class IODemo1
- {
- public static void main(String[] args) throws IOException
- {
- //fileInput();
- //fileOutput();
- //计算copyPic()方法执行所用的时间
- long start = System.currentTimeMillis();
- copyPic();
- long end = System.currentTimeMillis();
- System.out.println((end-start)+"毫秒");
- }
- public static void fileInput()throws IOException
- {
- FileInputStream fis = new FileInputStream("fos.txt");
- //字节流读取演示
- byte[] buf = new byte[1024];
- int len = 0;
- while((len = fis.read(buf))!= -1)
- {
- System.out.println(new String(buf,0,len));
- }
- //字节流特有读取方式。定义一个刚刚好的缓冲区,所以不用循环了
- //但是数据太大时会发生内存溢出。建议定义1024的整数倍。循环读取。
- byte[] buf1 = new byte[fis.available()];
- fis.read(buf1);
- System.out.println(new String(buf1));
- fis.close();
- }
- //字节流输出演示
- public static void fileOutput()throws IOException
- {
- FileOutputStream fos = new FileOutputStream("fos.txt");
- fos.write("djfasfs".getBytes());
- fos.close();
- }
- //字节流的缓冲区BufferedInputStream BufferedOutputStream
- public static void copyPic()
- {
- BufferedInputStream bufin = null;
- BufferedOutputStream bufout = null;
- try
- {
- bufin = new BufferedInputStream(new FileInputStream("1.jpg"));
- bufout = new BufferedOutputStream(new FileOutputStream("copy1.jpg"));
- int by = 0;
- while((by = bufin.read())!=-1)
- {
- bufout.write(by);
- }
- }
- catch (IOException e)
- {
- throw new RuntimeException("复制失败");
- }
- finally
- {
- try
- {
- if(bufin != null)
- bufin.close();
- }
- catch (IOException e)
- {
- throw new RuntimeException("读取流关闭失败");
- }
- try
- {
- if(bufout != null)
- bufout.close();
- }
- catch (IOException e)
- {
- throw new RuntimeException("输出流关闭失败");
- }
- }
- }
- }