【Java EE 初阶】文件操作

目录

1.什么是文件?

1.在cmd中查看指定目录的树形结构语法

2.文件路径

从当前目录开始找到目标程序(一个点)

返回到上一级目录,再找目标程序(两个点)

2.Java中文件操作

1.File概述

1.属性

2. 构造方法

3.常用方法

 代码展示:

4.常用方法2

3. 文件内容的读写---数据流

1.InputStream概述

2. FileInputStream

构造方法:

 1.输入数据到文件

3.字符流的输出流

4.Scanner类

5.printWrite类

 4.练习扫描文件并删除

1.步骤

2.代码:

3.结果

 4.进行普通文件的复制

1.步骤

2.代码:

3.结果: 


1.什么是文件?

1.狭义上的文件

硬盘上保存的数据,都是“文件”来组织的,本质上都是二进制或是字符组织的数组,被打包成一个文件存在硬盘上。常见的文件有图片(png),文本(txt),可执行文件(exe)等

80d0acdabee44141a65d054a87df0b17.png

2.广义上的文件

操作系统的主要功能就是对计算机资源进行统一管理与分配。对于Linux来说,所有的计算设备都会被描述(抽象)成文件。(例如:网卡,键盘,打印机)等

451af9d83f6745d09dd72f6a6343714c.png

 

树形结构组织随着文件越来越多,如何进行文件的组织呢?就是按照层级结构进行组织---也就是数据结构中的树形结构。而我们平时所谓的文件夹或者目录,就是专门用来存放管理信息的

3.在cmd中查看指定目录的树形结构

tree 文件名

2.文件路径

绝对路径:从根目录开始一直到目标程序的表示方式

相对路径:从当前目录开始,表示目标程序路径的方式

从当前目录开始找到目标程序(一个点)

语法:.+目标程序目录

返回到上一级目录,再找目标程序(两个点)

语法: ..+目标程序目录

2.Java中文件操作

92bc6807cc874e018ea621109bd0d7ba.png

  • 输入输出是以内存为参照物的,
  • 输入指的是从外部输入到内存,
  • 输出指的是把内存中的数据输出到外部(磁盘,网卡等)

1.File概述

1.属性

根据不同的系统返回系统默认的分隔符

ebd1e5329f2a4d7086ae193be6da1a3a.png

2. 构造方法

e9838529bd6a49b4b8ad2302874ea02e.png

一般常用第二种 

        File file = new File("D:\\temp");
        File file1 = new File("D:/temp");

反斜杠需要进行转义

3.常用方法

cb60620cd1a545958ef1944257a96c16.png

 代码展示:

public static void main(String[] args) throws IOException {
        // 指定绝对或相对路径并创建一个File对象
        File file = new File(".\\src\\main\\resources\\static\\image");
        // 获取父目录
        System.out.println(file.getParent());
        // 获取文件名
        System.out.println(file.getName());
        // 获取路径
        System.out.println(file.getPath());
        // 获取绝对路径
        System.out.println(file.getAbsolutePath());
        // 获取一个标准路径
        System.out.println(file.getCanonicalPath());
        // 获取是否已存在
        System.out.println(file.exists());
        // 获取是不是一个文件
        System.out.println(file.isFile());
        // 获取是不是一个目录
        System.out.println(file.isDirectory());

    }

平常我们使用标准路径获得的路径比较整洁

4.常用方法2

e993ec677be74d6d982d606e3d219699.png

1.创建一个文件

    public static void main(String[] args) throws IOException {
        File file = new File("D:\\temp\\test\\hello.txt");
        boolean res = file.createNewFile();
        if (res) {
            System.out.println("创建成功!");
        } else {
            System.out.println("创建失败");
        }
    }

97bc0cd2daa04b89a65878176b066347.png

 2.删除一个文件

    public static void main(String[] args) throws IOException {
        File file = new File("D:\\temp\\test\\hello.txt");
        boolean res = file.delete();

        if (res) {
            System.out.println("删除成功!");
        } else {
            System.out.println("删除失败");
        }
    }

48720631d4754711b314c132ed47ba1f.png

3返回file对象代表的目录下的所有文件,以file对象表示

    public static void main(String[] args) {
        File file = new File("D:\\temp\\test");

        //获取目录下的文件和子目录
        String[] list = file.list();
        System.out.println(Arrays.toString(list));

        //获取目录下的文件对象数组
        File[] files = file.listFiles();
        System.out.println(Arrays.toString(files));
    }

 3328b70f8d694d51b7f5e49961ae5cc3.png

4.创建单个目录

    public static void main(String[] args) {
        File file = new File("D:\\temp\\test01");

        //创建单个目录
        boolean res = file.mkdir();
        if (res) {
            System.out.println("创建成功!");
        } else {
            System.out.println("创建失败");
        }
    }

640094469585454b8193626772984db3.png

 5.创建一连串目录

    public static void main(String[] args) {
        File file = new File("D:/temp/test01/a/b/c");

        //创建单个目录
        boolean res = file.mkdirs();
        if (res) {
            System.out.println("创建成功!");
        } else {
            System.out.println("创建失败");
        }
    }

b183e513915a490d9a6827c05921882f.png

 6.修改文件名称

    public static void main(String[] args) {
        File file = new File("D:/temp/test/hello.txt");
        File file1 = new File("D:/temp/test/hi.txt");
        //创建单个目录
        boolean res = file.renameTo(file1);
        if (res) {
            System.out.println("修改成功!");
        } else {
            System.out.println("修改失败");
        }
    }

3d1636a62b8246dcbbda2c39bf0f1113.png

 7.查看文件读写状态

    public static void main(String[] args) {
        File file = new File("D:/temp/test/hello.txt");

        System.out.println(file.canRead());
        System.out.println(file.canWrite());
    }

03c2c1e93414436eadd2aa6cc71f2828.png

3. 文件内容的读写---数据流

48c9785ee31845f7b432aec65ed2488d.png

 63ac773fa4c14fd9b0828336112118c1.png

1.InputStream概述

InputStream只是一个抽象类,要使用还需要具体的实现类。从文件中读取,使用FileInputStream

 方法:

4b3773c1d6094099aef04303b5405357.png

c595444027c64d1695ca3edf14603ab9.png

1.读取文件中的数据

    public static void main(String[] args) throws IOException {
        File file = new File("D:/temp/test/hello.txt");
        InputStream inputStream = new FileInputStream(file);
        while (true) {
            int resd = inputStream.read();
            if (resd == -1) {
                break;
            }
            System.out.println(resd);
        }
    }

 67488af6d186483b8103c99946cd634b.png

 2.用数组保存读取出来的数据

    public static void main(String[] args) throws IOException {
        File file = new File("D:/temp/test/hello.txt");
        InputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[1024];
        while (true) {
            int resd = inputStream.read(bytes);
            if (resd == -1) {
                break;
            }
            for (int i = 0; i < resd; i++) {
                System.out.println(bytes[i]);
            }
        }
    }

 470b92310c3e4a7a8eeebb63f8a257e0.png

2. FileInputStream

构造方法:

ef2775f31af7470a922f9564aa68059e.png

 1.输入数据到文件

调用write方法就表示通过输出流,把内容写到指定的文件中

文件内容一般先写到缓冲区,缓冲区什么时候将内容写入文件,取决于操作系统

强制写入文件,调用 flash()方法,确保文件内容被立即写入

    public static void main(String[] args) throws IOException {
        File file = new File("D:/temp/test/hello.txt");
        //创建一个输出流
        FileOutputStream outputStream = new FileOutputStream(file);
        outputStream.write('a');
        outputStream.write('b');
        outputStream.write('c');
        //刷新缓存区
        outputStream.flush();
        //关闭输出流
        outputStream.close();

    }

db8ed591636f485681dcf0e0776406f6.png

5f146208fa2b4fbba9f72a9332eaccc3.png

用输出流的方式去写文件,会把之前的文件内容清空

2.读取字符

    public static void main(String[] args) throws IOException {
        File file = new File("D:/temp/test/hello.txt");
        //根据file对象创建一个Reader面向字符的输入流
        FileReader fileReader = new FileReader(file);
        while (true) {
            int res = fileReader.read();
            if (res == -1) {
                break;
            }
            //打印
            System.out.println(res);
        }
        //关闭输出流
        fileReader.close();

    }

3.字符流的输出流

    public static void main(String[] args) throws IOException {
        File file = new File("D:/temp/test/hello.txt");
        //根据file对象创建一个Reader面向字符的输入流
        FileWriter fileWriter = new FileWriter(file);
        fileWriter.write("你好");
        fileWriter.write("小锦鲤");
        //刷新
        fileWriter.flush();
        //关闭输出流
        fileWriter.close();

    }

 换行需要自己写转义字符\n进行换行

用输出流的方式去写文件,会把之前的文件内容清空

f04b8fecc6204e1bbeb57f2ffd67ecc8.png

6a3b7277b411475cb6d01adcb8712cef.png

4.Scanner类

    public static void main(String[] args) throws IOException {
        //根据file对象创建一个Reader面向字符的输入流
        FileInputStream inputStream = new FileInputStream("D:/temp/test/hello.txt");
        Scanner sc = new Scanner(inputStream,"UTF-8");
        while (sc.hasNext()) {
            String  s = sc.nextLine();
            System.out.println(s);
        }

    }

5.printWrite类

    public static void main(String[] args) throws IOException {
        //根据file对象创建一个Reader面向字符的输入流
        FileOutputStream outputStream = new FileOutputStream("D:/temp/test/hello.txt");
        PrintWriter printWriter = new PrintWriter(outputStream);
        printWriter.println("小锦鲤");
        printWriter.println("hello");
        printWriter.flush();
        printWriter.close();
    }

7acf3f0645f147e69111f8f2c175233b.png

 4.练习扫描文件并删除

1.步骤

e85b19c2b4ef4245b5bace32406c96d6.png

2.代码:

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class deleteFile {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要删除的文件的绝对路径");
        String path = sc.next();
        File file = new File(path);
        //检查是否有效
        //1.检查路径是否存在
        if (!file.exists()) {
            System.out.println("路径不存在哦~");
            return;
        }
        //2.检查是否为有效目录
        if (!file.isDirectory()) {
            System.out.println("不是有效目录哦~");
            return;
        }
        //让用户输入目标字符
        System.out.println("请输入要删除的文件名称");
        String name = sc.next();
        //判断名称是否合法
        //使用 "".equals(name) 避免出现异常
        if (name == null || "".equals(name)) {
            System.out.println("名称不可以为空哦~");
            return;
        }
        //递归进行删除
        delete(file, name);
    }

    public static void delete(File file, String name) throws IOException {
        //获取file下所有文件
        File[] files = file.listFiles();
        //递归终止条件
        if (files == null || files.length == 0) {
            return;
        }
        //遍历数组中的每个文件
        for (int i = 0; i < files.length; i++) {
            //判断是否为文件
            if (files[i].isFile()) {
                //是文件,判断是否为目标文件
                String fileName = files[i].getName();
                if (fileName.contains(name)) {
                    System.out.println("找到文件"+files[i].getCanonicalFile()+"是否确定删除?(Y/N)");
                    //接受用户的选择
                    Scanner sc = new Scanner(System.in);
                    String order = sc.next();
                    //删除(忽视大小写)
                    if ("Y".equalsIgnoreCase(order)) {
                        files[i].delete();
                        System.out.println(files[i].getCanonicalFile()+"删除成功~");
                    }
                }
            } else {
                //是目录则继续递归
                delete(files[i], name);
            }
        }


    }
}

3.结果

 a6a68e9f194d4d2fb319423fd472a082.png

 4.进行普通文件的复制

1.步骤

53a36c69a7d34b4b8644c10a28f061cd.png

2.代码:

import java.io.*;
import java.util.Scanner;

public class copyFile {
    public static void main(String[] args) throws FileNotFoundException {
        System.out.println("请输入要复制的文件的路径");
        Scanner sc = new Scanner(System.in);
        String sourceName = sc.next();
        //创建文件类实例
        File sourcefile = new File(sourceName);
        //判断文件是否存在
        if (!sourcefile.exists()) {
            System.out.println("文件不存在~");
            return;
        }
        //判断是否是文件
        if (!sourcefile.isFile()) {
            System.out.println("源文件不是一个有效的文件");
            return;
        }
        //接受用户输入的目标文件
        System.out.println("请输入目标文件路径(绝对路径)");
        String destName = sc.next();
        File destFile = new File(destName);
        //判断目标文件路径是否存在
        if (destFile.exists()) {
            System.out.println("目标文件已存在~");
        }
        //判断目标文件的夫目录是否存在
        if (!destFile.getParentFile().exists()) {
            System.out.println("目标文件路径父目录不存在");
        }
        //循环读取源文件到目标路径
        try {
            FileInputStream inputStream = new FileInputStream(sourcefile);
            FileOutputStream outputStream = new FileOutputStream(destFile);
            //定义byte【】的数组用来做输出型参数
            byte[] bytes = new byte[1024];
            while (true) {
                int len = inputStream.read(bytes);
                if (len == -1) {
                    break;
                }
                //写入目标文件
                outputStream.write(bytes);
                //刷新缓存
                outputStream.flush();
            }
            System.out.println("复制成功");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3.结果: 

 02780d5309a34032859949bafbfdfea7.png

2955e3c06a8346a4aeafe64a3dc4acce.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值