缓冲流Buffered
package stream; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.junit.jupiter.api.Test; /* * 1.缓冲流 * BufferedInputStream * BufferedOutputStream * BufferedReader * BufferedWriter * 把读写流用缓冲流包装起来就行 * * 2.作用:提高流的读取写入速度 * * */ public class BufferedTest { /* * 实现非文本文件的赋值 * */ @Test public void BufferedStreamTest(){ BufferedInputStream brs = null; BufferedOutputStream bos = null; try { File sfile = new File("zsben.jpg"); File tfile = new File("zsben3.jpg"); FileInputStream fis = new FileInputStream(sfile); FileOutputStream fos = new FileOutputStream(tfile); //用缓冲流包装读写流 brs = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); byte[] buffer = new byte[10]; int len; while((len = brs.read(buffer))!=-1) { bos.write(buffer,0,len); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { //关闭外层流的同时, 内层流也会自动被关闭 brs.close(); } catch (Exception e) { e.printStackTrace(); } try { bos.close(); } catch (Exception e) { e.printStackTrace(); } } } }
转换流
package stream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.junit.jupiter.api.Test; /* * 处理流之二:转换流 * OutputStreamWriter:字符输出流->字节输出流 * InputStreamWriter:字节输入流->字符输入流 * * 字符->字节 ('a'->97):即一个编码过程 * 字节->字符 (97->'a'):即一个解码过程 * * 发送过程时先把字符码转换成字节码进行发送, * 接收方接受时把字节码转换成字符码 * */ public class InputStreamReaderITest { @Test public void test1() throws IOException { //第二个参数:file保存时使用的编码方式 InputStreamReader isr= null; try { File file = new File("hello.txt"); FileInputStream fis = new FileInputStream(file); //字节流->字符流,注意后面的参数要带上编码方式,原来使用gbk编码存的,这儿换成UTF-8就会使中文字符乱码 isr = new InputStreamReader(fis,"gbk"); char [] buf = new char[20]; int len; while((len = isr.read(buf))!=-1) { String s = new String(buf,0,len); System.out.println(s); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } isr.close(); } }