Java基础学习(十)- IO流

2020-05-21  本文已影响0人  做个合格的大厂程序员

异常

概述

异常就是Java程序出现了不正常的情况。

Error

是Throwable的子类,用于指示合理的应用程序不应该试图捕获的严重问题,也就是说针对程序的Error的情况,Java程序本身是无能为力的。例如硬件层面的问题,内存不足等。

Exception

是Throwable的一种形式,它指出了合理的应用程序想要捕获的条件。也就是说针对程序发生的Exception的情况,我们需要处理的问题。

RuntimeException

是那些可能在Java虚拟机正常运行期间抛出的异常的超类。

Exception的分类

  1. 运行期的异常:在编译期不处理的,在程序运行时候出现了问题,需要我们回来改代码。
  2. 编译期的异常:在编译期就必须处理问题,否则程序不能通过编译,就更不能执行了。

代码示例

public class MyExceptionDemo {
    public static void main(String[] args) {

        method();
    }

    public static void method(){
        int a = 10;
        int b = 0;
        System.out.println(a / b);
    }
}

假设我们再这个例子里将分母变为0,则会报错。控制台会输出:

20200521081143

那么

java.lang.ArithmeticException: / by zero // 这是报错原因
at MyException.MyExceptionDemo.method(MyExceptionDemo.java:13) //报错的代码位置

所以如果产生Exception的问题,Java虚拟机会一步一步引导我们去找到问题的所在。从而去改正一些相关的异常。

异常处理

try...catch

public static void main(String[] args) {

        System.out.println("程序开始执行");
        method();
        System.out.println("程序结束执行");
    }

    public static void method(){
        try{
            int a = 10;
            int b = 0;
            System.out.println(a / b);
        }catch (ArithmeticException e){
            e.printStackTrace();
        }
    }
}

Throws

编译时异常

public static void method1() throws ParseException {
        String s = "2099-09-09";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = sdf.parse(s);
        System.out.println(d);
}

注意,如果抛出异常调用的时候必须捕获

try {
    method1();
} catch (ParseException e){
    e.printStackTrace();
}

File

File是文件和目录路径的抽象表现形式,也就是是说File可以封装成对象的。

下方f1,f2,f4为创建File对象的构造方法。

构造方法

//第一种构造
File f1 = new File("/Users/caoxiaozhu/Java/javaDemo/javaDemo.iml\n");

//第二种构造
File f2 = new File("/Users/caoxiaozhu/Java/javaDemo/","javaDemo.iml");

//第三种构造
File f3 = new File("/Users/caoxiaozhu/Java/javaDemo/");
File f4 = new File(f3,"javaDemo.iml");

创建功能

createNewFile() 创建一个文件

mkdir() 创建一个文件夹

创建一个目录(mac下)

String home = System.getProperty("user.home");
File f2 = new File(home + File.separator + "Desktop" + File.separator + "Java");
System.out.println(f2.mkdir());

(win下)

//d盘下创建dd文件夹
File f2 = new File("d:\\dd");
System.out.println(f2.mkdir());

ps:如果不指定路径,则默认创建在项目路径下

删除功能

delete()

String home = System.getProperty("user.home");
File f2 = new File(home + File.separator + "Desktop" + File.separator + "Java");
System.out.println(f2.delete());

判断功能

File f1 = new File("aaa");
f1.createNewFile(); //f1.mkdir() 创建一个文件夹

System.out.println("是否是文件夹:"+f1.isDirectory());
System.out.println("是否是文件:"+f1.isFile());
System.out.println("是否存在:"+f1.exists());

//打印
是否是文件夹:false
是否是文件:true
是否存在:true

获取功能

//获取绝对路径
System.out.println(f1.getAbsolutePath());

//获取相对路径
System.out.println(f1.getPath());

//获取文件名
System.out.println(f1.getName());

字节流

创建一个字节输出流

public static void main(String[] args) throws FileNotFoundException {
        //创建字节输出流
        FileOutputStream fos = new FileOutputStream("aa.txt");
}

创建一个字节输出流其实做了三件事:

完整代码

public static void main(String[] args) throws IOException {

    //创建字节输出流
    FileOutputStream fos = new FileOutputStream("aa.txt");
    
    //Write
    fos.write(66);
    fos.close();
}

写入字符串字节流

写入

fos.write("hello".getBytes());

换行

fos.write("\r\n".getBytes());

追加写入

FileOutputStream fos = new FileOutputStream("aa.txt",true);

异常处理

//        异常处理
    FileOutputStream fos = null;
    
    try {
        //创建并写入
        fos = new FileOutputStream("aa.txt");
        fos.write("hello world".getBytes());
    }catch (IOException e){
        //异常
        System.out.println(e);
        e.printStackTrace();
    }finally {
        //释放
        if(fos != null){
            try {
                fos.close();
            }catch (IOException e){
                e.printStackTrace();
            }    
        }
    }

ps:因为这种异常处理写起来太麻烦,所以现在异常以抛为主。

读取字节流

读取单个字节流

public static void main(String[] args) throws IOException {

    //创建读取字节流对象
    FileInputStream fim = new FileInputStream("aa.txt");

    //读数据的方法
    int by;
    while((by = fim.read()) != -1){
        System.out.print((char)by);
    }
    fim.close();
}

读取字节数组

FileInputStream fim = new FileInputStream("aa.txt");

byte[] bys = new byte[1024];
int len;
while((len=fim.read(bys))!=-1){
    System.out.println(new String(bys,0,len));
}
fim.close();

字节缓冲区流

字节流一次读写一个数组的速度比一次读写一个字节的速度块很多,这是加入了数组这样的缓冲区效果,java本身在设计的时候,也考虑到了这样的设计思想,所以提供了字节缓冲区流。

字节缓冲输出流

public static void main(String[] args) throws IOException {
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("aa.txt"));
    bos.write("hello leon world".getBytes());
    bos.close();
}

字节缓冲输入流

BufferedInputStream bis = new BufferedInputStream(new FileInputStream("aa.txt"));

int by;
while((by=bis.read())!=-1){
    System.out.print((char)by);
}
bis.close();

编码解码

    //编码
    String s = "您好";
    
    //byte[] bys = s.getBytes(); // 默认GBK
    byte[] bys = s.getBytes("UTF-8"); // 指定UTF-8编码
    System.out.println(Arrays.toString(bys));
    
    //解码
    String ss = new String(bys,"UTF-8");
    System.out.println(ss);

编码输出流

OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("demo.txt"),"UTF-8");
osw.write("您好");
osw.close();

编码输入流

InputStreamReader isr = new 

InputStreamReader(new FileInputStream("demo.txt"),"UTF-8");

char[] chs = new char[1024];
int len;
while ((len=isr.read(chs))!=-1){
    System.out.println(new String(chs,0,len));
}
osw.close();
isr.close();

FileReader & FileWritter (改进版)

 public static void main(String[] args) throws IOException {
        FileReader fileReader = new FileReader("demo.txt");
        FileWriter fileWriter = new FileWriter("demo1.txt");

//        第一种读取
//        int ch;
//        while ((ch=fileReader.read())!=-1){
//            fileWriter.write(ch);
//        }

//        第二种读取
        char[] chars = new char[1024];
        int len;
        while ((len=fileReader.read(chars))!=-1){
            fileWriter.write(chars,0,len);
        }
        fileReader.close();
        fileWriter.close();
    }

BufferedWriter && BufferedReader

public static void bufferedSteam() throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader("demo.txt"));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("demo1.txt"));

//        写数据
        bufferedWriter.write("hello");


//        第一种
//        int ch;
//        while ((ch=bufferedReader.read())!=-1){
//            System.out.print((char)ch);
//        }

//        第二种
        char[] chars = new char[1024];
        int len;
        while ((len=bufferedReader.read(chars))!=-1){
            System.out.println(new String(chars,0,len));
        }

        bufferedReader.close();
        bufferedWriter.close();
    }

特殊功能

fileWriter.newLine() 新起一行
fileWriter.flush() 刷新

举例:将集合中的元素一行一行输入到文本中

public static void newCharacter() throws IOException {
        Collection<String> collection = new ArrayList<String>();
        collection.add("hello");
        collection.add("world");
        collection.add("nihao");

        BufferedWriter fileWriter = new BufferedWriter(new FileWriter("demo2.txt"));
//        遍历
        for (String s : collection){
            fileWriter.write(s);
            fileWriter.newLine();
            fileWriter.flush();
        }
        fileWriter.close();
    }
上一篇 下一篇

猜你喜欢

热点阅读