案例一:读取文件
1 package com.bjsxt.io.byteIO; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileNotFoundException; 6 import java.io.IOException; 7 import java.io.InputStream; 8 9 /** 10 * 读取文件 11 * 12 */ 13 public class Demo01 { 14 15 public static void main(String[] args) { 16 //1、建立联系 File对象 17 File src = new File("e:/xp/test/a.txt"); 18 //2、选择流 19 InputStream is = null; //提升作用域 20 try { 21 is = new FileInputStream(src); 22 //3、操作不断读取 缓冲数组 23 byte[] car = new byte[10]; 24 int len = 0; //接受 实际读取大小 25 //循环读取 26 while(-1!=(len = is.read(car))) { 27 //输出 字节数组转成字符串 28 String info = new String(car,0,len); 29 System.out.println(info); 30 } 31 } catch (FileNotFoundException e) { 32 e.printStackTrace(); 33 System.out.println("文件不存在"); 34 } catch (IOException e) { 35 e.printStackTrace(); 36 System.out.println("读取文件失败"); 37 }finally { 38 try { 39 //4、释放资源 40 if (null != is) { 41 is.close(); 42 } 43 } catch (Exception e2) { 44 System.out.println("关闭文件输入流失败"); 45 } 46 } 47 48 } 49 50 }
案例二:写出文件
1 package com.bjsxt.io.byteIO; 2 3 import java.io.File; 4 import java.io.FileNotFoundException; 5 import java.io.FileOutputStream; 6 import java.io.IOException; 7 import java.io.OutputStream; 8 9 /** 10 * 写出文件 11 * 12 */ 13 public class Demo02 { 14 15 public static void main(String[] args) { 16 //1、建立联系 File对象,目的地 17 File dest = new File("e:/xp/test/test.txt"); 18 //2、选择流 文件输出流 OutputStream FileOutputStream 19 OutputStream os = null; 20 //以追加的形式写出文件 true是追加 false是覆盖 21 try { 22 os = new FileOutputStream(dest,true); 23 //3、操作 24 String str = "bjsxt is very good "; 25 //字符串转字节数组 26 byte[] data = str.getBytes(); 27 os.write(data,0,data.length); 28 29 os.flush(); //强制刷新出去 30 } catch (FileNotFoundException e) { 31 e.printStackTrace(); 32 System.out.println("文件未找到"); 33 } catch (IOException e) { 34 e.printStackTrace(); 35 System.out.println("文件写出失败"); 36 } finally { 37 //4、释放资源:关闭 38 try { 39 if (null != os) { 40 os.close(); 41 } 42 } catch (Exception e2) { 43 System.out.println("关闭输出流失败"); 44 } 45 } 46 } 47 48 }