JavaIO流

File类的实例化

  1. File类的一个对象,代表一个文件或一个文件目录(俗称:文件夹)
  2. File类声明在java.io包下
public class FileTest {
    /*
    1.如果创建File类的实例
        //File(String pathname) 通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例
        //File(String parent, String child) 从父路径名字符串和子路径名字符串创建新的File实例
        //File(File parent, String child) 从父抽象路径名和子路径名字符串创建新的File实例

    2.
      相对路径:相较于某个路径下,指明的路径
      绝对路径:包含盘符在内的文件或文件目录的路径
    3.路径分隔符
        windows:\\
        unix:/
     */
    @Test
    public void test(){
        //构造器1
        File file = new File("hello.txt"); //相对于当前的module
        File file1 = new File("F:\\javaDemo\\src\\com\\craziez\\ioTest\\he.txt");
        //构造器2
        File file2 = new File("F:\\javaDemo\\src\\com\\craziez\\","ioTest");
        //构造器3
        File file3 = new File(file2,"he.txt");
        System.out.println(file);
        System.out.println(file1);
        System.out.println(file2);
        System.out.println(file3);
    }
}

File类的常用方法1

File类的获取功能

  • public String getAbsolutePath():获取绝对路径

  • public String getPath() :获取路径

  • public String getName() :获取名称

  • public String getParent():获取上层文件目录路径。若无,返回null

  • public long length() :获取文件长度(即:字节数)。不能获取目录的长度。

  • public long lastModified() :获取最后一次的修改时间,毫秒值

如下两个方法适用于文件目录

  • public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组

  • public File[] listFiles() :获取指定目录下的所有文件或者文件目录的File数组

File类的重命名功能

  • public boolean renameTo(File dest):把文件重命名为指定的文件路径

    比如file1.renameTo(file2)为例:要想保证返回true,需要file1在硬盘存在,且file2不能在硬盘存在

public class FileTest {
    @Test
    public void test(){
        File file = new File("hello.txt");
        File file1 = new File("F:\\javaDemo\\src\\com\\craziez");
        System.out.println(file.getAbsolutePath());
        System.out.println(file.getName());
        System.out.println(file.getPath());
        System.out.println(file.getParent());
        System.out.println(file.length());
        System.out.println();
        System.out.println(file1.getAbsolutePath());
        System.out.println(file1.getName());
        System.out.println(file1.getPath());
        System.out.println(file1.getParent());
        System.out.println(file1.length());

        String[] s = file1.list();
        File[] files = file1.listFiles();
        for (File file2 : files) {
            System.out.println(file2);
        }
    }
    @Test
    public void test1(){
        File file1 = new File("hi.txt");
        File file2 = new File("F:\\javaDemo\\lol.txt");
        boolean renameTo = file1.renameTo(file2);
        System.out.println(renameTo);
    }
}

File类的常用方法2

File类的判断功能

  • public boolean isDirectory():判断是否是文件目录

  • public boolean isFile() :判断是否是文件

  • public boolean exists() :判断是否存在

  • public boolean canRead() :判断是否可读

  • public boolean canWrite() :判断是否可写

  • public boolean isHidden() :判断是否隐藏

File类的创建功能:创建硬盘中对应的文件或文件目录

  • public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false

  • public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。

如果此文件目录的上层目录不存在,也不创建。

  • public boolean mkdirs() :创建文件目录。如果上层文件目录不存在,一并创建

注意事项:如果创建文件或者文件目录没有写盘符路径,那么,默认在项目

路径下。

File类的删除功能

  • public boolean delete():删除文件或者文件夹

    删除注意事项:

    ​ Java中的删除不走回收站

    要删除一个文件目录,请注意该文件目录内不能包含文件或者文件目录

在这里插入图片描述

@Test
public void test2(){
    File file1 = new File("lol.txt");
    System.out.println(file1.isDirectory());
    System.out.println(file1.isFile());
    System.out.println(file1.exists());
    System.out.println(file1.isHidden());
    System.out.println(file1.canRead());
    System.out.println(file1.canWrite());
    System.out.println("-------------");
    File file2 = new File("F:\\javaDemo\\");
    System.out.println(file2.isDirectory());
    System.out.println(file2.isFile());
    System.out.println(file2.exists());
    System.out.println(file2.isHidden());
    System.out.println(file2.canRead());
    System.out.println(file2.canWrite());
}

@Test
public void test3() throws IOException {
    //文件的创建和删除
    File file = new File("hi.txt");
    if (!file.exists()){
        file.createNewFile();
        System.out.println("创建成功");
    }else{
        file.delete();
        System.out.println("删除成功");
    }

    //文件目录的创建
    File file1 = new File("F:\\JavaDemo\\SpringBoot");
    boolean mkr = file1.mkdir();
    if (mkr){
        System.out.println("创建成功");
    }
    File file2 = new File("F:\\JavaDemo\\Spring\\SpringCloud");
    boolean mkr2 = file2.mkdirs();
    if (mkr2){
        System.out.println("创建成功2");
    }
}

File类的对象通常作为参数传递到流的构造器中,指明读取或写入的"终点"

IO流概述与流的分类

I/O是Input/Output的缩写, I/O技术是非常实用的技术,用于处理设备之间的数据传输。如读/写文件,网络通讯等。

  • Java程序中,对于数据的输入/输出操作以“(stream)” 的

    方式进行。

  • java.io包下提供了各种“流”类和接口,用以获取不同种类的

    数据,并通过标准的方法输入或输出数据

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

IO流的体系结构

一、流的分类

  1. 操作的数据单位:字节流、字符流
  2. 数据的流向:输入流、输出流
  3. 流的角色:节点流、处理流

二、流的体系结构

		  抽象基类						   节点流(文件流)           缓冲流(处理流的一种)

​ InputStrem FileInputStream BufferedInputStream

​ OutputStream FileOutputStream BufferedOutputStream

​ Reader FileReader BufferedReader

​ Writer FileWriter BufferedWriter

在这里插入图片描述

FileReader读入数据的基本操作

  • read()的理解:返回读入的一个字符。若达到文件末尾则返回-1
  • 异常的处理:为了保证流资源一定可以执行关闭操作,需要使用try-catch-finally处理
  • 读入的文件一定要存在,否则会报FileNotFoundException
public class ioTest {
    /*
    将hello.txt的内容读入到程序中,并输出到控制台
     */
    @Test
    public void test1() {
        FileReader fileReader = null;
        try {
            //1.实例化File类对象,指明要操作的文件
            File file = new File("hello.txt");
            //2.提供具体的流
            fileReader = new FileReader(file);

            //3.数据的读入
            //read():返回读入的一个字符。如果达到文件末尾,返回-1
//        int data = fileReader.read();
//        while(data!=-1){
//            System.out.print((char)data);
//            data=fileReader.read();
//        }
            int data;
            while((data=fileReader.read())!=-1){
                System.out.print((char)data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //4.流的关闭操作
            try {
                if (fileReader!=null)
                    fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

FileReader中使用read(char[] cbuf)读入数据

    /*
        对read()操作升级:使用read的重载方法
     */
    @Test
    public void test2()  {
        FileReader fr = null;
        //1.File类的实例化
        File file = new File("hello.txt");
        //2.FileReader流的实例化
        try {
            fr = new FileReader(file);
            //3.读入的操作
            //read(char[] cbuf):返回每次读入到数组中的字符的个数。读到文件末尾返回-1
            char[] cbuf = new char[5];
            int len;
            while ((len=fr.read(cbuf))!=-1){
                for (int i = 0; i < len; i++) { //注意不能用cbuf.length遍历,理解输入流的过程
                    System.out.println(cbuf[i]);
                }
                //方式2
//                String str= new String(cbuf,0,len);
//                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.资源的关闭
            if (fr!=null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

FileWriter写出数据的操作

public class ioTest {
    /*
    从内存中写出数据到硬盘
    说明:
    1.输出操作,对应的file可以不存在。
    2.如果不存在,则会自动在硬盘中自动创建该文件
      如果存在:
              如果流使用的构造器是FileWriter(file,false) 则会对原有文件进行覆盖
                                FileWriter(file,true)  则会在原有文件基础上追加内容
                                (构造器默认为false)
     */
    @Test
    public void test1() throws IOException {
        //1.提供File类的对象,指明写出到的文件
        File file = new File("hello1.txt");

        //2.提供FileWriter的对象,用于数据的写出
        FileWriter fw = new FileWriter(file,);

        //3.写出操作
        fw.write("I have a dream!\n");
        fw.write("You should also have dream.");

        //4.流资源关闭
        fw.close();
    }
}

使用FileReader和FileWriter实现文件复制

public class ioTest {
    @Test
    public void test1()     {
        FileReader fr = null;
        FileWriter fw = null;
        try {
            //1.提供File类的对象,指明读入和写出的文件
            File srcfile = new File("hello.txt");
            File destfile = new File("hello1.txt");
            //2.创建输入流和输出流对象
            fr = new FileReader(srcfile);
            fw = new FileWriter(destfile);
            //3.数据的读入和写出
            char[] cbuf = new char[5];
            int len;//记录每次读入到cbuf数组中的字符的个数
            while ((len=fr.read(cbuf))!=-1){
                //每次写出len个字符
                fw.write(cbuf,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //4.流资源关闭
                if (fw!=null)
                    fw.close();
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                try {
                    if (fr!=null)
                        fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

字符流不能处理图片等字节数据!!!

FileInputStream不能读取文本文件的测试

如果用FileInputStream读取文本文件,因为UTF-8和GBK中英文字符都是一个字节,所以不会乱码,但是如果出现中文的话,中文占2个字节,则有可能会出现乱码情况(在控制台查看时),但是仅仅是用字节流复制文件的话是可以的(但是尽量别用)

public class FileInputOutPutStreamTest {
    @Test
    public void test1() throws IOException {
        //1.造文件
        File file = new File("hello.txt");
        //2.造流
        FileInputStream fis = new FileInputStream(file);

        //3.读数据
        byte[] buffer = new byte[5];
        int len;//记录每次读取的字节个数
        while ((len=fis.read(buffer))!=-1){
            String str = new String(buffer,0,len);
            System.out.println(str);
        }
        fis.close();
    }
}

对于文本文件(.txt .java .c .cpp等),使用字符流处理

对于非文本文件(.jpg .png .avi .mp4等),使用字节流处理

使用FileInputStream和FileOutPutStream读写非文本文件

public class FileInputOutPutStreamTest {
    @Test
    public void test1() throws IOException {
        File srcFile = new File("D:\\wallpaper\\Stay.jpg");
        File destFile = new File("Stay.jpg");

        FileInputStream fis = new FileInputStream(srcFile);
        FileOutputStream fos = new FileOutputStream(destFile);

        byte[] buffer = new byte[5];
        int len;
        while ((len=fis.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }

        fis.close();
        fos.close();
    }
}

Stay.jpg如下图:

在这里插入图片描述

使用FileInputStream和FileOutputStream复制文件的方法测试

public class FileInputOutPutStreamTest {
    @Test
    public void testCopyFile() throws IOException {
        String srcPath = "D:\\wallpaper\\Stay.jpg";
        String destPath = "Stay.jpg";
        long start = System.currentTimeMillis();
        copyFile(srcPath,destPath);
        long end = System.currentTimeMillis();
        System.out.println("复制操作花费的时间为:"+(end-start)+"ms");
    }

    public void copyFile(String srcPath,String destPath) throws IOException {
        FileInputStream fis = new FileInputStream(srcPath);
        FileOutputStream fos = new FileOutputStream(destPath);

        byte[] buffer = new byte[1024];//byte[]的长度会影响复制的时间
        int len;
        while ((len=fis.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        fis.close();
        fos.close();
        return;
    }
}

缓冲流(字节型)实现非文本的复制

  • 缓冲流能够提高读写效率,因为内部提供了一个缓冲区

  • 处理流就是套接在已有的流的基础上的流

  • 缓冲流:

    • BufferdInputStream
    • BufferedOutputStream
    • BufferedReader
    • BufferedWriter
public class BufferedTest {
    @Test
    public void test1() throws IOException {
        //1.造文件
        File srcFile = new File("D:\\wallpaper\\Stay.jpg");
        File destFile = new File("Stay.jpg");
        //2.造流
        //2.1 造节点流
        FileInputStream fis = new FileInputStream(srcFile);
        FileOutputStream fos = new FileOutputStream(destFile);
        //2.2 造缓冲流
        BufferedInputStream bis = new BufferedInputStream(fis);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        //3.复制操作
        byte[] buffer = new byte[5];
        int len;
        while ((len=bis.read(buffer))!=-1){
            bos.write(buffer,0,len);
         }

        //4.资源关闭
        //要求:先关闭外层的流,再关内层的流
        bis.close();
        bos.close();
        //说明:在关闭外层流的时候,内层流也会自动关闭。所以内层流的关闭可以省略
//        fis.close();
//        fos.close();
    }
}

缓冲流与节点流读写速度对比

public class FileInputOutPutStreamTest {
    @Test
    public void testCopyFile() throws IOException {
        String srcPath = "D:\\wallpaper\\Stay.jpg";
        String destPath = "Stay.jpg";
        long start = System.currentTimeMillis();
        copyFile(srcPath,destPath);
        long end = System.currentTimeMillis();
        System.out.println("节点流复制操作花费的时间为:"+(end-start)+"ms");//360
    }

    @Test
    public void testCopyFileWithBuffered() throws IOException {
        String srcPath = "D:\\wallpaper\\Stay.jpg";
        String destPath = "Stay.jpg";
        long start = System.currentTimeMillis();
        copyFileWithBuffered(srcPath,destPath);
        long end = System.currentTimeMillis();
        System.out.println("缓冲流复制操作花费的时间为:"+(end-start)+"ms");//10ms
    }

    public void copyFile(String srcPath,String destPath) throws IOException {
        FileInputStream fis = new FileInputStream(srcPath);
        FileOutputStream fos = new FileOutputStream(destPath);

        byte[] buffer = new byte[5];//byte[]的长度会影响复制的时间
        int len;
        while ((len=fis.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        fis.close();
        fos.close();
        return;
    }

    public void copyFileWithBuffered(String srcPath,String destPath) throws IOException {
        FileInputStream fis = new FileInputStream(srcPath);
        FileOutputStream fos = new FileOutputStream(destPath);

        BufferedInputStream bis = new BufferedInputStream(fis);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        byte[] buffer = new byte[5];
        int len;
        while ((len=bis.read(buffer))!=-1){
            bos.write(buffer,0,len);
        }
        bis.close();
        bos.close();
    }
}

缓冲流(字符型)实现文本文件的复制

public class BufferedTest {
    @Test
    public void test1() throws IOException {
        //1.造文件
        File srcFile = new File("F:\\javaDemo\\hello.txt");
        File destFile = new File("hello1.txt");
        //2.造流
        //2.1 造节点流
        FileReader fr = new FileReader(srcFile);
        FileWriter fw = new FileWriter(destFile);
        //2.2 造缓冲流
        BufferedReader br = new BufferedReader(fr);
        BufferedWriter bw = new BufferedWriter(fw);
        //3.复制操作
        //方式1:
//        char[] cbuf = new char[1024];
//        int len;
//        while ((len=br.read(cbuf))!=-1){
//            bw.write(cbuf,0,len);
//         }

        //方式2 使用String
        String data;
        while ((data=br.readLine())!=null){
            bw.write(data);//data中不包含换行符
            bw.newLine(); //提供换行操作
        }

        //4.资源关闭
        br.close();
        bw.close();

    }
}

转换流概述与InputStreamReader的使用

在这里插入图片描述

  • 转换流提供了在字节流和字符流之间的转换、

    • 转换流属于字符流(看后缀)
  • Java API提供了两个转换流:

    • InputStreamReader:将一个字节的InputStream转换为字符的Reader
    • OutputStreamWriter:将一个字符的Writer转换为字节的OutputStream
  • 字节流中的数据都是字符时,转成字符流操作更高效。

  • 很多时候我们使用转换流来处理文件乱码问题。实现编码和

    解码的功能。

  • 解码:字节、字节数组—>字符数组、字符串

  • 编码:字符数组:字符串—>字节、字节数组

public class InputStreamReaderTest {
    @Test
    public void test1() throws IOException {
        FileInputStream fis = new FileInputStream("hello.txt");
//        InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集
        //参数2指明了字符集,具体使用哪个字符集,取决于hello.txt保存时使用的字符集
        InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
        char[] cbuf = new char[20];
        int len;
        while ((len=isr.read(cbuf))!=-1){
            String str = new String(cbuf,0,len);
            System.out.println(str);
        }
        
        isr.close();
    }
}

转换流实现文件的读入和写出

public class InputStreamReaderTest {
    @Test
    public void test1() throws IOException {
        FileInputStream fis = new FileInputStream("hello.txt");
        FileOutputStream fos = new FileOutputStream("hello_gbk.txt");
        InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
        OutputStreamWriter osr = new OutputStreamWriter(fos,"gbk");
        char[] cbuf = new char[20];
        int len;
        while ((len=isr.read(cbuf))!=-1){
            osr.write(cbuf,0,len);
        }
        
        isr.close();
        osr.close();
    }
}

多种字符编码集的说明

编码表的由来

计算机只能识别二进制数据,早期由来是电信号。为了方便应用计算机,让它可以识

别各个国家的文字。就将各个国家的文字用数字来表示,并一一对应,形成一张表。

这就是编码表。

常见的编码表

  • ASCII:美国标准信息交换码。用一个字节的7位可以表示。

  • ISO8859-1:拉丁码表。欧洲码表用一个字节的8位表示。

  • GB2312:中国的中文编码表。最多两个字节编码所有字符

  • GBK:中国的中文编码表升级,融合了更多的中文文字符号。最多两个字节编码

  • Unicode:国际标准码,融合了目前人类使用的所有字符。为每个字符分配唯一的字符码。所有的文字都用两个字节来表示。

  • UTF-8:变长的编码方式,可用1-4个字节来表示一个字符

标准的输入、输出流

  • System.in:标准的输入流。默认从键盘输入

  • System.out:标准的输出流。默认从控制台输出

  • 重定向:System类的setIn(InputStream)/setOut(OutputStream)方式重新指定输入和输出的流

public class OtherStreamTest {
    /*
    例题:从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续
            进行输入操作,直至当输入“e”或者“exit”时,退出程序

    方法1:使用Scanner()实现。调用next()方法返回一个字符串
    方法2:使用System.in实现。System.in --> 转换流 --> BufferedReader的readLine()
     */
    @Test
    public void test1() throws IOException {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        while (true){
            String data = br.readLine();
            if ("e".equalsIgnoreCase(data)||"exit".equalsIgnoreCase(data)){
                System.out.println("程序结束");
                break;

            }
            String upperCase = data.toUpperCase();
            System.out.println(upperCase);
        }
        br.close();
    }
}

打印流的使用

实现将基本数据类型的数据格式转化为字符串输出

  • 打印流:PrintStreamPrintWriter

  • 提供了一系列重载的print()和println()方法,用于多种数据类型的输出

  • PrintStream和PrintWriter的输出不会抛出IOException异常

  • PrintStream和PrintWriter有自动flush功能

  • PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节。

在需要写入字符而不是写入字节的情况下,应该使用 PrintWriter 类。

System.out返回的是PrintStream的实例

在这里插入图片描述

数据流的使用

  • DataInputStream和DataOutputStream

在这里插入图片描述

public class OtherStreamTest {

    @Test
    public void test1() throws IOException {
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
        dos.writeUTF("Cez");
        dos.flush();
        dos.writeInt(23);
        dos.flush();
        dos.writeBoolean(true);
        dos.flush();

        dos.close();
    }

    @Test
    public void test2() throws IOException {
        DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
        //注意:读取时要按照写入时的顺序!!!
        String name = dis.readUTF();
        int age = dis.readInt();
        boolean isMale = dis.readBoolean();  
        System.out.println("name:"+name);
        System.out.println("age:"+age);
        System.out.println("isMale:"+isMale);

        dis.close();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值