Android面试-Java基础-异常 IO流

来源:互联网 发布:ubuntu修改ip地址命令 编辑:程序博客网 时间:2024/05/17 01:57

异常

这里写图片描述

异常处理的方式
1、捕捉异常

trycatchfinally

2、抛出异常

throws

throw和throws
a:throws
用在方法声明后面,跟的是异常类名
可以跟多个异常类名,用逗号隔开
表示抛出异常,由该方法的调用者来处理
b:throw
用在方法体内,跟的是异常对象名
只能抛出一个异常对象名
表示抛出异常,由方法体内的语句处理

private static int divide(int num1, int num2) throws Exception {....} public char charAt(int index){    if(index < 0){        throw new StringIndexOutOfBoundException(index);    }    .... }

异常注意事项
a:子类重写父类方法时,子类的方法必须抛出相同的异常或父类异常的子类。(父亲坏了,儿子不能比父亲更坏)
b:如果父类抛出了多个异常,子类重写父类时,只能抛出相同的异常或者是他的子集,子类不能抛出父类没有的异常
c:如果被重写的方法没有异常抛出,那么子类的方法绝对不可以抛出异常,如果子类方法内有异常发生,那么子类只能try,不能throws

I/O流

字节流 字符流 输出流 OutputStream Writer 输入流 InputStream Reader

1、FileInputStream和FileOutputStream

FileInputStream fis = null;FileOutputStream fos = null;try {    fis = new FileInputStream("xxx.mp3");     fos = new FileOutputStream("copy.mp3");    int b;    while((b = fis.read()) != -1) {        fos.write(b);    }} finally {    try {        if(fis != null)            fis.close();    }finally {        if(fos != null)            fos.close();    }}

read()方法读取的是一个字节,为什么返回是int,而不是byte
因为字节输入流可以操作任意类型的文件,比如图片音频等,这些文件底层都是以二进制形式的存储的,如果每次读取都返回byte,有可能在读到中间的时候遇到111111111那么这11111111是byte类型的-1,我们的程序是遇到-1就会停止不读了,后面的数据就读不到了,所以在读取的时候用int类型接收,如果11111111会在其前面补上24个0凑足4个字节,那么byte类型的-1就变成int类型的255了这样可以保证整个数据读完,而结束标记的-1就是int类型

2、BufferedInputStream和BufferedOutputStream
使用了装饰设计模式
内置了一个缓存区,先将数据读写到缓存区中,再通过缓存区进行读写

BufferedInputStream bis = null;BufferedOutputStream bos = null;try {    bis = new BufferedInputStream(new FileInputStream("xxx.mp3"));    bos = new BufferedOutputStream(new FileOutputStream("copy.mp3"));     int b;    while((b = bis.read()) != -1) {         bos.write(b);    }} finally {    try {        if(fis != null)            bis.close();    }finally {        if(fos != null)            bos.close();    }}

3、FileWriter和FileReader

 FileReader fr = null; FileWriter fw = null; try{     fr= new FileReader("aaa.txt"); //创建字符输入流,关联aaa.txt     fw= new FileWriter("bbb.txt"); //创建字符输出流,关联bbb.txt     int len;     char[] arr = new char[1024*8];   //创建字符数组     while((len = fr.read(arr)) != -1) {  //将数据读到字符数组中         fw.write(arr, 0, len);   //从字符数组将数据写到文件上     } }finally {    try {        if(fr != null)            fr.close();    }finally {        if(fw != null)            fw.close();    }}

4、装饰设计模式

interface Coder {    public void code();}class Student implements Coder {    @Override    public void code() {        System.out.println("javase");        System.out.println("javaweb");    }}class HeiMaStudent implements Coder {    private Student s;                      //获取到被包装的类的引用    public ItcastStudent(Student s) {       //通过构造函数创建对象的时候,传入被包装的对象        this.s = s;    }    @Override    public void code() {                    //对其原有功能进行升级        s.code();        System.out.println("数据库");        System.out.println("ssh");        System.out.println("安卓");        System.out.println(".....");    }}