Java IO笔记

来源:互联网 发布:最小截图软件 编辑:程序博客网 时间:2024/06/03 13:49

IO的分类

  • 第一种分法
    • 输入流
    • 输出流
  • 第二种分法
    • 字节流
    • 字符流
  • 第三种分法
    • 节点流
    • 处理流

简单的IO读写例子

public class Test {    public static void main(String[] args) {        FileInputStream fis = null;        FileOutputStream fos = null;        try{            fis = new FileInputStream("I:/from.txt");            fos = new FileOutputStream("I:/to.txt");            byte[] buffer = new byte[100];            //read的第三个参数表示读取一次最多读多少数据,一般肯定是不大            //于buffer字节数组的大小的,返回值temp是本次读取了多少字节            int temp = fis.read(buffer,0,buffer.length);            //write的第三个参数指写多少个字节的数据            fos.write(buffer,0,temp);            //String s = new String(buffer);            //System.out.println(s);        }        catch (Exception e){            System.out.println(e);        }         finally {            try {                fis.close();                fos.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }}

但通常文件不可能如此小,因此读取的时候buffer不可能给定一个很大的空间。所以肯定要循环去读取。

大文件的读写方法

public class Test {    public static void main(String[] args) {        FileInputStream fis = null;        FileOutputStream fos = null;        try{            fis = new FileInputStream("I:/from.txt");            fos = new FileOutputStream("I:/to.txt");            byte[] buffer = new byte[1024];            //当返回值为-1时说明读取结束            while(true){                int temp = fis.read(buffer,0,buffer.length);                if(temp == -1){                    break;                }                fos.write(buffer,0,temp);            }        }        catch (Exception e){            System.out.println(e);        }        finally {            try {                fis.close();                fos.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }}

以上都是以字节为基础进行操作的,下面以字符为基础

基于字符流操作

其实字符流的操作和字节流差不多,只不过用于生成对象的类不一样而已,其他大同小异:

public class Test {    public static void main(String[] args) {        FileReader fr = null;        FileWriter fw = null;        try{            fr = new FileReader("I:/from.txt");            fw = new FileWriter("I:/to.txt");            char[] buffer = new char[1024];            int temp = fr.read(buffer,0,buffer.length);            //当返回值为-1时说明读取结束            while(true){                temp = fr.read(buffer,0,buffer.length);                if(temp == -1){                    break;                }                fw.write(buffer,0,temp);            }        }        catch (Exception e){            System.out.println(e);        }        finally {            try {                fr.close();                fw.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }}

后续补充中…

0 0
原创粉丝点击