BufferedInputSream和BufferedOutputSream,,,
package cd.itcast.bufferinputstream; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * 缓冲输入字符流 * @author Administrator * */ public class Demo1 { public static void main(String[] args) throws IOException { //找到目标 File file = new File("E:\\a.txt"); //建立输入通道 FileInputStream fileInputStream = new FileInputStream(file); //建立缓冲输入字节流 //fileInputStream具有读写文件的能力,bufferiInputStream没有。 BufferedInputStream bufferInputStream = new BufferedInputStream(fileInputStream); //读取文件 int content=0; while ((content = bufferInputStream.read())!=-1) { System.out.print((char)content); } //关闭资源,关闭bufferInputStream,就是关闭fileInputStream bufferInputStream.close(); } }
2、
package cd.itcast.bufferinputstream; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /* * 1、使用BufferedOutputStream写数据的时候,他的write()方法是先把数据写到它内部维护的字节数组中。 * 2、使用BufferedOutputStream写数据的时候,如果需要把数据写到硬盘上,需要调用flush()方法,或者是close()方法,或者是内部维护的字节数组已经填满的时候。 */ public class BufferOutputStream { public static void main(String[] args) throws IOException { //找到目标文件 File file = new File("E:\\a.txt"); //建立数据通道 FileOutputStream fileOutputStream = new FileOutputStream(file); //建立缓冲输出字节流对象 BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); //数据写出,此时写到内存里了 bufferedOutputStream.write("hello word!".getBytes()); //写出数据到硬盘bufferedOutputStream.flush()或者Close(); bufferedOutputStream.close(); } }
3、复制图片
package cd.itcast.bufferinputstream; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class CopyTu { public static void main(String[] args) throws IOException { File infile = new File("E:\\图片\\1.jpg"); File desFile = new File("E:\\1.jpg"); FileInputStream fileInputStream = new FileInputStream(infile); FileOutputStream fileOutputStream = new FileOutputStream(desFile); BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); //read()中如果传入了缓冲数组,则内容是存储到数组中的,返回值是存储到数组中的字节个数。 //read()如果没有传入缓冲数组,那么返回值是读取到的内容。 int content=0; //边读边写 while ((content=bufferedInputStream.read())!=-1) { bufferedOutputStream.write(content); //bufferedOutputStream.flush();不要刷,写一个字节,一刷,这样就没意义啦 } /*执行close()的时候,执行了flush(). * public void close() throws IOException { try { flush(); } catch (IOException ignored) { } out.close(); }*/ bufferedOutputStream.close(); bufferedInputStream.close(); } }