一、分类情况
1.Stream指字节流;
2.Reader和Writer指字符流;
字节流 字符流
输入流 InputStream(父类) Reader(父类)
输出流 OutputStream(父类) Writer(父类)
流中数据 二进制字节(8bit) Unicode字符(16bit)
二、读文件访问
1.使用文件输入流打开指定文件
文本文件:字符输入流FileReader
二进制文件:字节输入流FileInputStream
2.读取文件数据
3.关闭输入流
三、写文件访问
1.使用文件输出流打开指定文件
文本文件:字符输出流FileWriter
二进制文件:字节输出流FileOutputStream
2.将数据写入文件(清空写入,添加写入)
3.关闭输入流
四、代码演示
1.字符输入流
FileReader fr = null; try { fr = new FileReader(args[0]); char [] buf = new char[100]; int n = fr.read(buf); while(n != -1){ for(int i=0;i<n;i++){ System.out.println(buf[i]); } n = fr.read(buf); } } catch (IOException e) { e.printStackTrace(); }finally{ if(fr!=null){ try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } }
2.字符输出流
String [] text = {"这是第一行 ", "需要FileWriter ", "访问结束需要关闭文件 "}; FileWriter fw = null; try { fw = new FileWriter(args[0]);//清空方式 //fw = new FileWriter(args[0],true); //添加方式 char [] buf; for(String str : text){ buf = str.toCharArray(); for(int i =0;i<str.length();i++){ System.out.println(buf[i]); } fw.write(buf, 0, str.length()); //fw.write(str, 0, str.length()); } } catch (IOException e) { e.printStackTrace(); }finally{ if(fw!=null){ try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } }
3.包装字符输入流
FileReader fr = null; BufferedReader br = null; try { fr = new FileReader(args[0]); br = new BufferedReader(fr); String line = br.readLine(); while(line != null){ System.out.println(line); line = br.readLine(); } } catch (IOException e) { e.printStackTrace(); }finally{ if(br!=null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } }
4.包装字符输出流
String [] text = {"这是第一行 ", "需要FileWriter ", "访问结束需要关闭文件 "}; FileWriter fw = null; BufferedWriter bw = null; try { fw = new FileWriter(args[0]);//清空方式 //fw = new FileWriter(args[0],true); //添加方式 bw = new BufferedWriter(fw); for(String str : text){ bw.write(str); bw.newLine(); } } catch (IOException e) { e.printStackTrace(); }finally{ if(bw!=null){ try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } }
5.包装字节输出流
FileOutputStream fos = null; BufferedOutputStream bos = null; ObjectOutputStream oos = null; try { fos = new FileOutputStream(args[0]); bos = new BufferedOutputStream(fos); oos = new ObjectOutputStream(bos); oos.writeInt(0); oos.writeFloat(1.1f); oos.writeBoolean(true); oos.writeUTF("1111"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(oos!=null){ try { oos.close(); } catch (IOException e) { } } }
6.包装字节输入流
FileInputStream fis = null; ObjectInputStream ois = null; try { fis = new FileInputStream(args[0]); ois = new ObjectInputStream(fis); int i = ois.readInt(); float f = ois.readFloat(); Boolean b =ois.readBoolean(); String str = ois.readUTF(); System.out.println(i+"-"+f+"-"+b+"-"+str); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(ois!=null){ try { ois.close(); } catch (IOException e) { } } }