字节流分为:输入流(InputStream)和输出流(outputStream)
(1)字节流读入读出
package com.songyan.bytedemo; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class Demo1 { public static void main(String[] args) throws IOException { testIn2(); } /** * 字节读入1 * @throws IOException */ public static void testIn() throws IOException { FileInputStream in=new FileInputStream("Demo3.java"); int by=0; while((by=in.read())!=-1) { System.out.print((char)by); } in.close(); } /** * 字节读入2 * @throws IOException */ public static void testIn2() throws IOException { FileInputStream in=new FileInputStream("Demo3.java"); byte[] arr=new byte[8192]; int len=0; while((len=in.read(arr))!=-1) { System.out.print(new String(arr,0,len)); } in.close(); } /** * 字节读入3 * @throws IOException */ public static void testIn3() throws IOException { FileInputStream in=new FileInputStream("Demo3.java"); //available()可以获取文件的大小,直接创建一个和文件大小相同的数组 //但是这种方法只适用于文件大小不太大的情况 byte[] arr=new byte[in.available()]; System.out.print(new String(arr)); in.close(); } /** * 字节输出 * @throws IOException */ public static void testOut() throws IOException { FileOutputStream out=new FileOutputStream("demo1.txt"); out.write("hahahha".getBytes()); out.close(); } }
(2)字节流练习题
package com.songyan.bytedemo; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * 拷贝一个图片 * @author Administrator * */ public class Test { public static void main(String[] args) { FileInputStream in=null; FileOutputStream out=null; try { in=new FileInputStream("E:\\sy\\java\\javaee\\【阶段07】Spring\\spring-day01\\spring-day01\\code\\struts_crm\\WebContent\\images\\info.png"); out=new FileOutputStream("info.png"); byte[] arr=new byte[8192]; int len=0; while((len=in.read(arr))!=-1) { out.write(arr); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { if(in!=null) in.close(); if(out!=null) out.close(); } catch (IOException e) { e.printStackTrace(); } } } }