文件路径4种写法:
1
| String filePath = "temp01";
|
1 2 3
| String filePath = "D:\\course\\JavaProjects\\02-JavaSE\\chapter08\\temp01"; String filePath = "D:/course/JavaProjects/02-JavaSE/chapter08/temp01"; String filePath = "D:"+File.separator+"course"+File.separator+"JavaProjects"+File.separator+"02-JavaSE"+File.separator+"chapter08"+File.separator+"temp01";
|
输入输出流标准写法:
- 创建流对象:
- 创建输入流对象会抛出FileNotFoundException异常,该异常可以细化处理
- 创建输出流对象时若文件不存在则自动创建,默认为覆盖写入,如果要追加方式写入,在构造方法参数列表后加一个true
- 进行读写操作:抛出IOException
- 关闭流对象:抛出IOException
字符流和字节流:
- 字节流可以用于所有文件
- 字符流编程比较方便(可用readline方法),但只能用于纯文本文件
copy代码范例(字节流):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| FileInputStream fIn = null; FileOutputStream fOut = null; byte[] buff = new byte[1024]; int temp = 0; try { fIn = new FileInputStream("F://test//1.avi"); 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 { if(fIn!=null) { try { fIn.close(); }catch(IOException e) { e.printStackTrace(); } } if(fOut!=null) { try { fOut.close(); }catch(IOException e) { e.printStackTrace(); } } }
|
copy不规范代码(字符流使用readline):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| 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();
|