Java基础——文件操作

File类:

文件和目录路径名的抽象表示,主要用于文件和目录的创建,查找与删除操作。

无论该路径下是否存在文件或目录,都不影响File对象的创建。

路径不区分大小写

    // 构造方法创建文件对象
    String file1 = "d:\\a.txt";
    File f1 = new File(file1);

    // 构造方法可以支持父路径名与子路径名拼接的方式构建
    File f2 = new File("d:\\parent", "b.txt");

    // 支持file对象与子路径名的拼接
    File f3 = new File("d:");
    File f4 = new File(f3,"c.txt");

常用方法:

绝对路径:从盘符开始的路径,是完整路径

相对路径:相对于项目根目录的路径

        // 获取绝对路径
        System.out.println(f4.getAbsolutePath());
        // 获取构造路径
        System.out.println(f4.getPath());
        // 获取文件名
        System.out.println(f4.getName());
        // 获取文件长度(字节),文件夹是没有大小概念的,若构造方法中的路径不存在,则返回0
        System.out.println(f4.length());

判断方法:

        if(f1.exists()){// 判断是否存在
            // 是否是文件夹
            System.out.println(f1.isDirectory());
            // 是否是文件
            System.out.println(f1.isFile());
        }

创建与删除:

        // 当且仅当该文件不存在时创建新文件
        f1.createNewFile();
        // 创建文件夹
        f1.mkdir();
        // 创建多级文件夹
        f1.mkdirs();
        // 删除文件/文件夹,当文件夹里有内容时不能删除
        File f5 = new File("d:\\aaa");
        System.out.println(f5.delete());

遍历:

        // 返回String数组,表示该File目录中所有子文件或目录
        File f6 = new File("f:\\Test");
        String[] filename1 = f6.list();
        for (String name :
                filename1) {
            System.out.println(name);
        }

        // 返回File数组,表示该File目录中所有子文件或目录
        File[] filename2 = f6.listFiles();
        for (File name :
                filename2) {
            System.out.println(name);
        }

文件过滤器:

        File[] txtfiles = dir.listFiles(new FileFilter() {
            @Override
            // 该方法判断pathname是否应该包含在File目录中,是则返回true
            public boolean accept(File pathname) {
                return pathname.getName().endsWith(".txt")||pathname.isDirectory();
            }
        });

IO字节流:

输入流:从其它设备(硬盘)读取到内存中的流

输出流:从内存写出到其它设备上的流

计算机中的一切文件皆是字节

字节输出流(FileOutputStream):

 

创建:

当创建一个流对象时必须传入文件路径或File对象,若不存在则在相应位置下创建,若存在则会被清空覆盖。

    public static void OutputStream01() throws FileNotFoundException {
        // 通过文件名创建流对象
        FileOutputStream o1 = new FileOutputStream("a.txt");

        // 通过File对象创建流对象
        File f1 = new File("b.txt");
        FileOutputStream o2 = new FileOutputStream(f1);
    }

写出:

    public static void OutputStream02() throws IOException {
        // 通过文件名创建流对象
        FileOutputStream o1 = new FileOutputStream("a.txt");
        // 写出字节
        o1.write(97);

        byte[] b1 = "您好".getBytes();
        o1.write(b1);

        byte[] b2 = "我爱中国".getBytes();
        o1.write(b2, 1, 3);
        // 关闭资源
        o1.close();
    }

追加写:

        // true表示在这个文件后追加数据,false表示清空,默认为false
        FileOutputStream o1 = new FileOutputStream("a.txt", true);

换行:

在windows中,换行符号为\r\n

    public static void OutputStream04() throws IOException {
        // true表示在这个文件后追加数据,false表示清空,默认为false
        FileOutputStream o1 = new FileOutputStream("a.txt");
        byte[] s = {96,97,98,99,100};
        for (int i = 0; i < s.length; i++)
        {
            o1.write(s[i]);
            o1.write("\r\n".getBytes());
        }
        o1.close();
    }

 

字节输入流(FileInputStream):

 

按照字节读取:

按照字节读取,每次读取一个字节并提升为int类型。

    public static void InputStream01() throws IOException {
        FileInputStream i1 = new FileInputStream("a.txt");
        int b;
        // read每次读取一个字节的数据,末尾返回-1
        while((b = i1.read() )!= -1){
            System.out.println((char)b);
        }
        i1.close();
    }

按照字节数组读取:

    public static void InputStream02() throws IOException {
        FileInputStream i1 = new FileInputStream("a.txt");
        byte[] bs = new byte[2];
        int len;
        // read通过字节数组去读数据,将读取到的内容按字节数组的长度放进字节数组中去
        while((len = i1.read(bs) )!= -1){
            System.out.println(new String(bs));
        }
        i1.close();
    }

文件拷贝:

    public static void copy() throws IOException {
        FileInputStream i = new FileInputStream("img.JPG");
        FileOutputStream o = new FileOutputStream("imgcopy.JPG");
        byte[] bs = new byte[1024];
        int len;
        while((len = i.read(bs)) != -1){
            o.write(bs, 0, len);
        }

        o.close();
        i.close();
    }

IO字符流:

 

用字节流读取文本内容时,若遇到中文字符,当编码格式为GBK时一个中文占用两个字节,而编码格式为UTF-8时,一个中文占用3个字节。

处理文本文件时,应考虑使用java提供的字符流。

字符流每次读取的是一个字符,字节流每次读取的是一个字节。 

 字符输入流(FileReader):

    public static void FileReader01() throws IOException {
        FileReader r1 = new FileReader("a.txt");
        int len;
        while ((len = r1.read() )!= -1){
            System.out.println((char)c);
        }
    }

    public static void FileReader02() throws IOException {
        FileReader r1 = new FileReader("a.txt");
        int len;
        char[] cs = new char[2];
        while ((len = r1.read(cs) )!= -1){
            System.out.println(new String(cs));
        }
    }

字符输出流(FileWriter):

字符输出流和字节输出流的使用方式大致相似,flush方法可以将缓冲区内的数据写入到文件中,同时不会关闭流。

    public static void FileWriter01() throws IOException {
        FileWriter w1 = new FileWriter("a.txt", true);
        w1.write(97);

        char[] cs1 = {'m', 'n'};
        w1.write(cs1);

        char[] cs2 = "今天是周日".toCharArray();
        w1.write(cs2);

        w1.write("\r\n我要吃火锅");
        
        w1.close();
    }

缓冲流(Buffered)

缓冲流是在创建流对象时,创建一个内置的默认大小缓冲区域,通过缓冲区读写,减少IO次数,提高读写的效率。

 

字节缓冲流(BufferedInputStream/BufferedOutputStream)

字节缓冲流相对于字节流处理能力更高效更强,且使用方式相同。

// 创建字符缓冲输入流与输出流        
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("a.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("a.txt"));

字符缓冲流(BufferedReader/BufferedWriter)

使用方式与字符流的使用方式相似,唯一区别是readLine方法可以读取整行,newLine方法写换行。

    public static void Buffered02() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("a.txt"));
        String line = null;
        while ((line = br.readLine()) != null){
            System.out.println(line);
        }
        br.close();
    }

    public static void Buffered03() throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));
        bw.write("现在");
        bw.newLine();
        bw.write("应该睡觉");
        bw.close();
    }

转换流:

编码:按照某种规则将字符存储到计算机中,计算机中的数据都是二进制的。

解码:按照某种规则将计算机中的数据解析出来。

字符集:一个系统所支持的所有字符集合。

 

InputStreamReader:

读取字节,按照指定编码解码成字符。

        InputStreamReader isr = new InputStreamReader(new FileInputStream("d:\\新建文本文档.txt"), "utf-8");
        int len;
        while ((len = isr.read()) != -1){
            System.out.println((char)len);
        }
        isr.close();

        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("d:\\新建文本文档.txt"),"GBK");
        osw.write("好累");
        osw.close();

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值