Java期末根据提纲复习(三)

17)自定义异常 extends Exception
a. 为了创建和使用自定义的异常,必须先定义一个异常类。自定义异常类通常从Exception类派生而成。
b. 有了自定义的异常类后,只要在可能抛出异常的方法后使用throw关键字,就可以在方法中抛出异常
c. 自定义异常的形式:class MyException extends Exception { …}

(参考:https://blog.csdn.net/guojinyu_001/article/details/81282189
(参考:https://blog.csdn.net/qq_18505715/article/details/73196421?utm_source=blogxgwz8

1)运行时异常:即RuntimeException及其之类的异常。这类异常在代码编写的时候不会被编译器所检测出来,是可以不需要被捕获,但是程序员也可以根据需要进行捕获抛出。常见的RUNtimeException有:NullpointException(空指针异常),ClassCastException(类型转换异常),IndexOutOfBoundsException(数组越界异常)等。
2)编译异常:RuntimeException以外的异常。这类异常在编译时编译器会提示需要捕获,如果不进行捕获则编译错误。常见编译异常有:IOException(流传输异常),SQLException(数据库操作异常)等。
能写一个最简单的就已经吹唢呐了!:

class Demo extends Exception{
 public int s1,s2;
 public void Way() throws Exception {
  if(s1>s2)
  {
   throw  new Exception("s1不能大于s2");
  }
  else {
   System.out.println("无异常!");
  }
 }
}
public class Test2 {
 public static void main(String[] args) throws Exception {
  Demo d1=new Demo();
  d1.s1=10;
  d1.s2=9;
  d1.Way();
  Demo d2=new Demo();
  d2.s1=9;
  d2.s2=10;
  d2.Way();
 }  
}
Exception in thread "main" java.lang.Exception: s1不能大于s2
 at Demo.Way(Test2.java:11)
 at Test2.main(Test2.java:23)

其实还存在很多问题(比如命名,在实际运用中也不会这么写,哎)
这是老师写的一道题:
eg:Account类: 银行账号
属性: balance 余额
方法: getBalance() 获取余额
方法: deposit() 存钱
方法: withdraw() 取钱
OverdraftException: 透支异常,继承Exception

public class OverdraftException extends Exception{
    public OverdraftException(String msg) {
        super(msg);
    }
}
import java.io.IOException;
/*方法: getBalance() 获取余额
        方法: deposit() 存钱
        方法: withdraw() 取钱
        OverdraftException: 透支异常,继承Exception*/
public class Accout {
    private double balance;
    public Accout(double balance) {
        this.balance = balance;
    }
    public double getBalance(){
        return balance;
    }
    public void deposit(double money){
        balance=balance+money;
    }
    public void withdraw(double money) throws OverdraftException {
        if(money>balance){
                throw new OverdraftException("取钱金额不能大于余额!!!");
        }else{
            balance=balance-money;
        }
    }
    public static void main(String[] args) {
        Accout accout=new Accout(2000);
        accout.deposit(1000);
        try {
            accout.withdraw(4000);
        } catch (OverdraftException e) {
            e.printStackTrace();
        }
        System.out.println(accout.getBalance());
    }
}

那我在这里最好奇的还是super的用法
(网上解释这个的太少了,对菜鸟好不友好)
super(message);意思是带着子类的构造函数的参数message调用父类的构造函数。如果不写这一句,那么父类的message就没有值。你可以输出一下getMessage()输出一下消息。
(试了一下,暂时只能理解成给Exception实例化命名?)

18)JAVA标准的输入和输出
a. 标准输入为键盘 public static final InputStream in
b. 标准输出为显示器 public static final PrintStream out
这是老师给的一段代码,我是理解不透(先放着):

import java.io.*;
public class FDemo {
    public static void main(String[] args) {
        listAll("d:\\test","d:\\test\\TRUMP.txt");
    }
    public static void listAll(String strfile,String dfile){
        File f=new File(strfile);
        File[] files=f.listFiles();
        for(File ff:files){
            if(!ff.isDirectory()){
                if(ff.getName().endsWith(".java")) {
                    System.out.println(ff.getPath());
                    merge(ff.getPath(),dfile);
                }
            }else{
                listAll(ff.getPath(),dfile);
            }
        }
    }
    public static void merge(String sfile,String dfile){
        try (FileReader fr = new FileReader(sfile);
             BufferedReader bis=new BufferedReader(fr);
             FileWriter fw=new FileWriter(dfile);
             BufferedWriter bos = new BufferedWriter(fw);
        ) {
           String str="";
           while((str=bis.readLine())!=null){
              // System.out.println((char)c);
               bos.write(str);
               bos.newLine();
           }
        }catch (FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

(参考:https://blog.csdn.net/YSJS99/article/details/105377945
(参考:https://blog.csdn.net/zhaoyanjun6/article/details/54292148/
引用:
输入字节流InputStream:
1.InputStream是所有的输入字节流的父类,它是一个抽象类。
2.ByteArrayInputStream、StringBufferInputStream、FileInputStream是三种基本的介质流,它们分别从Byte 数组、StringBuffer、和本地文件中读取数据。
3.PipedInputStream 是从与其它线程共用的管道中读取数据。
4.ObjectInputStream 和所有FilterInputStream 的子类都是装饰流(装饰器模式的主角)。
我觉得不用懂那么多,先懂1.2就行了
参考文里有现成的应用代码,写的挺好(偷偷照搬):
照搬的代码地址

package IO1;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class A1 {
 public static void main(String[] args) {
  A1 a1 = new A1();
  //电脑d盘中的abc.txt 文档
  String filePath = "D:/abc.txt" ;
  String reslut = a1.readFile( filePath ) ;
        System.out.println( reslut ); 
 }
 /**
  * 读取指定文件的内容
  * @param filePath : 文件的路径
  * @return  返回的结果
  */
 public String readFile( String filePath ){
  FileInputStream fis=null;
  String result = "" ;
  try {
   // 根据path路径实例化一个输入流的对象
   fis  = new FileInputStream( filePath );
   //2. 返回这个输入流中可以被读的剩下的bytes字节的估计值;
   int size =  fis.available() ;
   //3. 根据输入流中的字节数创建byte数组;
   byte[] array = new byte[size];
   //4.把数据读取到数组中;
   fis.read( array ) ; 
   //5.根据获取到的Byte数组新建一个字符串,然后输出;
   result = new String(array); 
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }catch (IOException e) {
   e.printStackTrace();
  }finally{
   if ( fis != null) {
    try {
     fis.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  return result ;
 }
}

输出字节流 OutputStream:
1.OutputStream 是所有的输出字节流的父类,它是一个抽象类。
2.ByteArrayOutputStream、FileOutputStream 是两种基本的介质流,它们分别向Byte 数组、和本地文件中写入数据。
3.PipedOutputStream 是向与其它线程共用的管道中写入数据。
4.ObjectOutputStream 和所有FilterOutputStream 的子类都是装饰流。
照搬代码的地址

package IO1;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class A2 {
 public static void main(String[] args) {
  A2 a2 = new A2();
  //电脑d盘中的abc.txt 文档
  String filePath = "D:/abc.txt" ;
  //要写入的内容
  String content = "今天是2017/1/9,天气很好" ;
  a2.writeFile( filePath , content  ) ;
 }
 /**
  * 根据文件路径创建输出流
  * @param filePath : 文件的路径
  * @param content : 需要写入的内容
  */
 public void writeFile( String filePath , String content ){
  FileOutputStream fos = null ;
  try {
   //1、根据文件路径创建输出流
   fos  = new FileOutputStream( filePath );
   //2、把string转换为byte数组;
   byte[] array = content.getBytes() ;
   //3、把byte数组输出;
   fos.write( array );
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }catch (IOException e) {
   e.printStackTrace();
  }finally{
   if ( fos != null) {
    try {
     fos.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
}

(这个需要试手,留一个fiag,试手了把代码也贴这)
(flag2:字符流的Reader和Writer)

19)scanner类的作用,输入数据的方法
Scanner reader = new Scanner(System.in)
reader.nextInt();
用Scanner类输入其实已经做得很熟练了,不过这里再把以前的记一下
nextInt()/nextFloat()/nextLine()/next()
next()和nextLine()都是接受字符串,但nextLine()接受的字符串不受空格的限制只受回车的限制、而next()遇空格就截止
nextLine()和next():
如果从键盘上接受的数据时先接收数值型再接收字符串类型时,若数值型接收语句后跟的nextLine()则要写两次nextLine(),因为第一遍是为接收前面数值型数据回车符,第二遍才可以接收字符串,而next()不受影响。

20)File类和RandomAccessFile类,数据操作的方法,注意写模式
a. 通过File类, 可以获得文件属性和状态
b. 通过RandomAccessFile类可以处理任何类型的数据文件
c. File类的构造方法
d. public File(String path)
e. public File(String path, String name)
f. public File(File dir, String name)
常用方法:
a) canRead()/canWrite()判断该文件是否可读写
b) delete()删除文件
c) mkdir()创建目录
d) renameTo()用于修改文件名称
e) isDirectory():用于判断文件对象是否为目录
f) isFile()判断文件对象是否为文件
g) getName()用于获得文件对象名称
h) getPath()用于获得路径名称
i) getParent()用于获得目录名称
j) getAbsolutePath()用于获得绝对路径名称
k) list()如果文件是目录,则获得该目录中所有文件名,
l) lastModified():用于获得文案最后修改时间
m) Length()用于获得文件的字节长度
(flag3:试手)

21)输入流和输出流的含义
(参考:https://blog.csdn.net/bing63983627/article/details/6610906?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase
东西读入内存就是输入流
东西从内存写到记录存储输出流

输入流是将资源数据读入到缓冲Buffer中,输出流是将缓冲Buffer中的数据按照指定格式写出到一个指定的位置,所以这两个流一般同时使用,才有意义。

22)FileInputStream和FileOutputStream,使用字节数组,注意追加模式
a. 主要功能是建立一个与文件相关的输入/输出流, 并提供从文件中读取/写入一个字节或一组数据的方法
b. 构造方法:
c. public FileInputStream(String name) throws FileNotFoundException
d. public FileInputStream(File file) throws FileNotFoundException
重要方法:
a) Int available()获得文件可读长度
b) void close() 关闭输入流
c) Int read() 从文件中读取一个字节长度的内容
d) Int read(byte[] b)从文件中读取一个字节数组的长度
e) Int read(byte [] b,int off,int len) 从文件读取指定长度的字节到数组中。
f) long skip(long n)文件指针跳过字符数
f. public FileOutputStream(String name) throws FileNotFoundException
g. public FileOutputStream(String name, boolean append) throws FileNotFoundException
h. public FileOutputStream(File file) throws FileNotFoundException
i. public FileOutputStream(File file, boolean append) throws FileNotFoundException
常用方法
a) void close()关闭输出流
b) Void write(byte b)throws IOException写入一个字节数据
c) Void write(byte [] b)throws IOException 连续写入一个字节数组的数据
d) Void read(byte [] b,int off,int len)连续写入一定长度的字节数组数据
(这个需要和(18)结合起来看,还需要自己敲!哎)

猜你喜欢

转载自blog.csdn.net/qq_44229840/article/details/106461766
今日推荐