• JavaEE——IO


    一、文件的存储位置

    💡 文件就是在我们的计算机中,为了实现某种功能或某个软件的部分功能为目的而定义的一个单位.计算机中的存储器分为内存外存,文件一般存储在外存(硬盘)之中.

    二、什么是路径

    💡 文件路径分为绝对路径相对路径.

    2.1 绝对路径

    是从盘符开始的路径,例如C:\ProgramFiles\Java\jdk1.8.0_191\bin.

    2.2 相对路径:

    基于当前路径表示,使用“…/”或"./"开头来表示上一级目录,其中“./”可以省略不写.

    三、File类

    3.1 常用方法

    public class Demo2 {
        public static void main(String[] args) throws IOException {
            File file = new File("test2.txt");
            System.out.println(file.exists());
            System.out.println(file.isDirectory());
            System.out.println(file.isFile());
            System.out.println("==============");
            file.createNewFile();
            System.out.println(file.exists());
            System.out.println(file.isDirectory());
            System.out.println(file.isFile());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    3.2 创建目录

    public class Demo4 {
        public static void main(String[] args) {
            File file = new File("test/aa/b");
            file.mkdirs();
            System.out.println(file.isDirectory());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    3.3 重命名

    public class Demo5 {
        public static void main(String[] args) {
            File file1 = new File("./test2.txt");
            File file2 = new File("./test1.txt");
            file1.renameTo(file2);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    四、文件的读

    💡首先要打开一个文件,然后使用InputStream来间接修改文件,最后使用close来关闭文件,为了防止中间代码执行出现异常,我们这里用try-with-resource语法来解决这个问题,try中的代码执行结束,自动释放文件描述符表和内存资源.

    文件描述符表是有上限的,如果忘记关闭,后续的文件则会打不开.

    public class Demo7 {
        public static void main(String[] args)  {
            try(InputStream inputStream = new FileInputStream("test1.txt")) {
                Scanner scanner = new Scanner(inputStream);
                String s = scanner.next();
                System.out.println(s);
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    五、文件的写

    💡Writer是一个抽象类,不能直接实例化对象,所以使用它的子类FileWriter.

    public class Demo8 {
        public static void main(String[] args) {
            try(Writer writer = new FileWriter("test1.txt")) {
                writer.write("hello world");
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

  • 相关阅读:
    自底向上的构建二叉堆
    【笔记】excel怎么把汉字转换成拼音
    STL标准模板库
    【全栈】vue3.0 + golang 尝试前后端分离【博客系统1.1】有进展了
    新型人工智能技术让机器人的识别能力大幅提升
    oracle-buffer cache
    【Java 进阶篇】深入了解 JavaScript 的 innerHTML 属性
    递归算法 -- 解决全排列问题
    java面向对象进阶
    正则-贪婪模式/非贪婪模式
  • 原文地址:https://blog.csdn.net/qq_59854519/article/details/126572839