--- title: Java SE笔记: IO-输入输出规范代码 date: 2016-08-23 21:20:00 updated: 2016-08-23 21:20:00 description: "IO-输入输出规范代码" categories: [个人笔记] tags: [Java, Java SE笔记] --- ### 文件路径4种写法: - 相对路径,相对当前而言,在当前路径下找: ```java String filePath = "temp01"; ``` - 绝对路径: ```java String filePath = "D:\\course\\JavaProjects\\02-JavaSE\\chapter08\\temp01";//普通写法,需要用转义字符 String filePath = "D:/course/JavaProjects/02-JavaSE/chapter08/temp01";//反斜杠写法,windows系统下支持 String filePath = "D:"+File.separator+"course"+File.separator+"JavaProjects"+File.separator+"02-JavaSE"+File.separator+"chapter08"+File.separator+"temp01";//最标准写法:用系统相关默认名称分隔符 ``` ### 输入输出流标准写法: 1. 创建流对象: - 创建输入流对象会抛出FileNotFoundException异常,该异常可以细化处理 - 创建输出流对象时若文件不存在则自动创建,默认为覆盖写入,如果要追加方式写入,在构造方法参数列表后加一个true 2. 进行读写操作:抛出IOException 3. 关闭流对象:抛出IOException ### 字符流和字节流: - 字节流可以用于所有文件 - 字符流编程比较方便(可用readline方法),但只能用于纯文本文件 ### copy代码范例(字节流): ```java FileInputStream fIn = null; FileOutputStream fOut = null; byte[] buff = new byte[1024]; int temp = 0; try { //定义输入流对象,会抛出FileNotFoundException fIn = new FileInputStream("F://test//1.avi"); //定义输出流对象,文件不存在则自动创建,如果要追加方式写入,在构造方法参数列表后加一个true fOut = new FileOutputStream("F://test//2.avi"); //读写的操作 while((temp = fIn.read(buff)) != -1) { fOut.write(buff, 0, temp); } fOut.flush();//为了保证数据完全写入硬盘,推荐用强制刷新写入 }catch(FileNotFoundException e)//输入流抛出异常的细化处理 { e.printStackTrace(); }catch(IOException e)//读写操作的异常处理 { e.printStackTrace(); }finally//关闭流对象,写在finally语句块中确保一定执行 { if(fIn!=null)//防止空指针异常 { try { fIn.close(); }catch(IOException e) { e.printStackTrace(); } } if(fOut!=null) { try { fOut.close(); }catch(IOException e) { e.printStackTrace(); } } } ``` ### copy不规范代码(字符流使用readline): ```java BufferedReader br = new BufferedReader(new FileReader("Copy03.java")); BufferedWriter bw = new BufferedWriter(new FileWriter("c:/Copy03.java")); String temp = null; int count = 0;//用于防止在文件最后写一个换行符 while(true) { count++; temp = br.readLine(); if(temp==null) { break; } if(count>1) { bw.newLine();//如果不写换行符,文件不会换行 } bw.write(temp); } bw.flush(); br.close(); bw.close(); ```