1.java io总述
最主要的四个基类:InputStrem,OutputStream,Reader,Writer .其余大部分io类都是继承这些基类的。
按照输入输出分类,分为输入和输出两大类:如InputStream,Reader是输入,OutputStream,Writer是输出。
按照格式分类,分为字节流和字符流:InputStream/OutputStream是字节流,适用于非文本文件;Reader/Writer是字符流,适用文本文件。
按照功能分类,分为节点流和处理流。节点流即可以直接作用在文件上的流。如InputStream is=new InputStrem(new File("a.jpg"))
处理流是包装在节点流的,即以节点流为参数。如BufferedInputStream bis=new BufferedInputStream(new InputStream("b.txt"))
处理流是装饰器模式
2.File类
所有的输入输出流的对象都是文件。File类代表文件对象。File类不仅能代表存在的文件和目录,也可以创建新的目录或尚不存在的整个目录路径。通过File,可以实现对文件的基本操作:查看特性(文件大小,最后修改日期等),删除文件,重命名文件等。
3.输入输出类
输入:从文件中读到内存中,为输入
输出: 从内存(程序)中写到文件里,为输出。
以输入字符流为例:
public void testFileReader() { //1.实例化file对象,指明要操作的文件对象 FileReader fr = null; try { File file = new File("hello.txt"); //2.实例化具体的流FileReader fr= null; fr = new FileReader(file); //3.数据的读入 while (fr.read() != -1) { System.out.println(fr.read()); } } catch (IOException e) { e.printStackTrace(); } finally { //4.关闭流 if (fr != null) { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } }
其他类型的输入输出操作,只需要改动2,3点即可。
4.处理流
以字节缓冲流为例:复制图片文件
public void BufferedInputOutputStreamTest(){ File file=new File("a.jpg"); File file2=new File("a1.jpg"); //字节流 BufferedInputStream bis= null; BufferedOutputStream bos= null; try { FileInputStream fis=new FileInputStream(file); FileOutputStream fos=new FileOutputStream(file2); //缓冲流 bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); byte[] buffer=new byte[1024]; int len; //从源文件读出 while ((len=bis.read(buffer))!=-1){ //写入目的文件 bos.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { //关闭流;只需要关闭外层流,内层流在外层关闭时会自动关闭 try { bis.close(); } catch (IOException e) { e.printStackTrace(); } try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } }
注:尤其在文件很大时,使用缓冲流会比不使用缓冲流快很多。
常见的处理流还有一种:InputStreamReader/OutputStreamReader 将字节流转化为字符流
5.其他
其他的流,比如数组流 ByteArrayInputStream/CharArrayReader,数据流 DataInputStream等都大同小异同,直接查看api即可。
值得注意的一点是:RandomAccessFile并不是继承以上四个基类中的任何一个,而是直接派生自Object.
RandomAccessFile只支持搜寻方法,并且只使用于文件。