Java 输入输出和异常

2018-05-17  本文已影响0人  dpengwang

Java 输入输出和异常

读取控制台输入

Java的控制台输入由System.in完成。为了获得一个绑定到控制台的字符流,可以把System.in包装在一个BufferedReader 对象中来创建一个字符流。

下面是创建BufferedReader的基本语法:

public class IOtest {
    public static void main(String args[]) throws IOException{
        char c;
        BufferedReader  br =  new BufferedReader(new InputStreamReader(System.in));
        System.out.println("please enter some thing");
        do{
            c = (char)br.read();//字符串的话使用readline()
            System.out.print(c);    
        }while(c!='q');     //字符串的话这里使用equals(object)
    }

即先创建了BufferReader然后再调用它的read方法接收控制台输入

FileInputStream:

该流用于从文件读取数据,它的对象可以用关键字new来创建。有多种构造方法可用来创建对象。可以使用字符串类型的文件名来创建一个输入流对象来读取文。

File f = new File("C:/java/hello");     //创建文件对象
InputStream f = new FileInputStream(f);  
or
InputStream  af = new FileInputStream(f)

main方法中要throws IOException

从文件中读取内容

public class FileIOtest {
    public static  void main(String arhs[]) throws IOException{
        File f = new File("D:/hello.txt");     //创建文件对象
        InputStream af = new FileInputStream(f);
        int  size =af.available();
        for (int i=0;i<size;i++){
            System.out.println((char)af.read());
        }   
    }
    }

FileOutputStream

该类用来创建一个文件并向文件中写入数据,如果打开的文件不存在,那么改流会创建该文件,创建输入流:

OutputStream f = new FileOutputStream("C:/java/hello")
//or
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);

public class FileIOtest {
    public static  void main(String arhs[]) throws IOException{
        File f = new File("D:/hello.txt");     //创建文件对象
        OutputStream of =  new FileOutputStream(f);
        int[] arraya = {1,2,3,4,5};
        for (int i=0;i<arraya.length;i++){
            of.write(arraya[i]);
        }
        of.close();
    }
    }

上述读写的方式可能会产生乱码的问题,可以通过构建reader和writer来指定编码方式

//读文件
File f = new File("xxx");
FileInputStream fip = new FileInputStream(f);
InputStramReader  reader = new InputStreamReader(fip,"UTF-8")
while(reader.ready()){  //是ready
    System.out.print(reader.read())
}

//写
File f = new File("xxx");
FileOutputStream  fop = new FileOutputStream(f);
OutputStreamWriter writer = new OutputStreamWriter(fop,"UTF-8")
writer.append("xx")//写入到缓冲区,在文件关闭的时候写入文件

文件打开后记得关闭

Java创建目录

File类中有两个方法可以用来创建文件夹:

import java.io.File;
public class CreateDir{
    String dirname = "/tmp/user/java/bin";
    File d = new File(dirname);
    d.mkdirs();
}

查看某路径下的所有文件:list()

判断是否为目录:isDirectory()

Java Scanner类

用来获取用户输入,创建Scanner:

Scanner s = new Scanner(System in);

next()使用:

public class Scannertest {
       public static void main(String args[]){
           Scanner  sc =  new Scanner(System.in);
           while(sc.hasNext()){
               String next = sc.next();
               System.out.println("repeated"+next);
       }}}

nextLine使用:

public class Scannertest {
       public static void main(String args[]){
           Scanner  sc =  new Scanner(System.in);
           while(sc.hasNext()){
               String next = sc.next();
               System.out.println("repeated"+next);
       }}}

更精确的表达法是:hasNextXXX 比如hasNextFloat

Java 异常处理

捕获异常

try
{
   // 程序代码
}catch(ExceptionName e1)
{
   //Catch 块
}

多重捕获块:

 try{
    // 程序代码
 }catch(异常类型1 异常的变量名1){
    // 程序代码
 }catch(异常类型2 异常的变量名2){
    // 程序代码
 }catch(异常类型2 异常的变量名2){
    // 程序代码
 }

finally:

try{
    
}catch(){
    
}catch(){
    
}finally{
    
}  //不论异常是否发生,finally中的内容都会被执行

throws/throw关键字:

如果一个方法没有捕获一个检查性异常,那么该方法必须使用throws 关键字来声明。throws关键字放在方法签名的尾部。

也可以使用throw关键字抛出一个异常,无论它是新实例化的还是刚捕获到的。多个异常之间可以用逗号隔开。

声明自定义异常:

所有异常都必须是Throwable的子类,如果是检查性异常类,则需要继承Exception类,如过是运行时异常类,那么需要继承RuntimeException类

class ValueException extends Exception{
    private double amount;
    public ValueException(double amount){
        this.amount  =amount;
    }
    public double getAmount(){
        return amount;
    }
}
 class moneny{
     double amount;
     public moneny(double amount){
         this.amount =amount;
     }
     public void cutmoney(double cut) throws ValueException{
         if (cut <= this.amount){
             System.out.println("we can do it");
         }
         else{
             double need  = cut -this.amount;
             throw new ValueException(need);
         }
     }}
class Exceptiontest{
  public static void main(String args[]){
      moneny m = new moneny(100);
      try{
          m.cutmoney(200);
      }
      catch (ValueException e) {
        System.out.println("we need "+e.getAmount());
    }
  }       
}

异常类也就是一个特殊的类,使用的时候也要传入参数,只不过他是在一个方法创建的时候 在方法后面写上抛出语句(throw xxexception),在方法里面写上具体抛出的异常(带参数),在方法调用的时候抛出并catch

上一篇 下一篇

猜你喜欢

热点阅读