• 总结File类的用法及InputStream、OutputStream的用法


    前言

    本篇博客,博主将从File类的用法及InputStream、OutputStream的用法几个方面详细介绍,坐好板凳发车啦~~

    一.File类

    1.1File类概述

    Java中通过Java.io.File类来对一个文件(包括目录)进行抽象的描述。注意,有File对象,并不代表真实存在该文件。

    我们先来看看File类中的常见属性、构造方法和方法。

    属性

    修饰符及类型                             属性                                                      说明

    static String                        pathSeparator                依赖于系统的路径分隔符,String类型的表示

    static char                          pathSeparator                依赖于系统的路径分隔符,char类型的表示

    构造方法

    签名                                                                                     说明

    File(File parent,String child)             根据父目录+孩子文件路径,创建一个新的File实例

    File(String pathnam)                        根据文件路径创建一个新的File实例,路径可以是绝对路径

                                                                                                 或是相对路径

    File(String parent,String child)            根据父目录+孩子文件路径,创建一个新的File实例,

                                                                                             父目录用路径表示

    方法

     

    1.2示例代码

    1.2.1.观察get系列的特点和差异

    1. import java.io.File;
    2. import java.io.IOException;
    3. public class Main {
    4. public static void main(String[] args) throws IOException {
    5. File file = new File("..\\hello-world.txt"); // 并不要求该⽂件真实存在
    6. System.out.println(file.getParent());
    7. System.out.println(file.getName());
    8. System.out.println(file.getPath());
    9. System.out.println(file.getAbsolutePath());
    10. System.out.println(file.getCanonicalPath());
    11. }
    12. }
    13. 运行结果
    14. ..
    15. hello-world.txt
    16. ..\hello-world.txt
    17. D:\代码练习\⽂件⽰例1\..\hello-world.txt
    18. D:\代码练习\hello-world.txt

    1.2.2.普通文件的创建和删除

    1. import java.io.File;
    2. import java.io.IOException;
    3. public class Main {
    4. public static void main(String[] args) throws IOException {
    5. File file = new File("hello-world.txt"); // 要求该⽂件不存在,才能看
    6. System.out.println(file.exists());
    7. System.out.println(file.isDirectory());
    8. System.out.println(file.isFile());
    9. System.out.println(file.createNewFile());
    10. System.out.println(file.exists());
    11. System.out.println(file.isDirectory());
    12. System.out.println(file.isFile());
    13. System.out.println(file.createNewFile());
    14. }
    15. }
    16. 运行结果
    17. false
    18. false
    19. false
    20. true
    21. true
    22. false
    23. true
    24. false

    删除操作

    1. import java.io.File;
    2. import java.io.IOException;
    3. public class Main {
    4. public static void main(String[] args) throws IOException {
    5. File file = new File("some-file.txt"); // 要求该⽂件不存在,才能看到相
    6. System.out.println(file.exists());
    7. System.out.println(file.createNewFile());
    8. System.out.println(file.exists());
    9. System.out.println(file.delete());
    10. System.out.println(file.exists());
    11. }
    12. }
    13. 运行结果
    14. false
    15. true
    16. true
    17. true
    18. false

    1.2.3.观察deleteExit的现象

    1. import java.io.File;
    2. import java.io.IOException;
    3. public class Main {
    4. public static void main(String[] args) throws IOException {
    5. File file = new File("some-file.txt"); // 要求该⽂件不存在,才能看到相
    6. System.out.println(file.exists());
    7. System.out.println(file.createNewFile());
    8. System.out.println(file.exists());
    9. file.deleteOnExit();
    10. System.out.println(file.exists());
    11. }
    12. }
    13. 运行结果
    14. false
    15. true
    16. true
    17. true

    1.2.4.观察目录的创建

    1. import java.io.File;
    2. import java.io.IOException;
    3. public class Main {
    4. public static void main(String[] args) throws IOException {
    5. File dir = new File("some-dir"); // 要求该⽬录不存在,才能看到相同的现
    6. System.out.println(dir.isDirectory());
    7. System.out.println(dir.isFile());
    8. System.out.println(dir.mkdir());
    9. System.out.println(dir.isDirectory());
    10. System.out.println(dir.isFile());
    11. }
    12. }
    13. 运行结果
    14. false
    15. false
    16. true
    17. true
    18. false
    1. import java.io.File;
    2. import java.io.IOException;
    3. public class Main {
    4. public static void main(String[] args) throws IOException {
    5. File dir = new File("some-parent\\some-dir"); // some-parent 和 so
    6. System.out.println(dir.isDirectory());
    7. System.out.println(dir.isFile());
    8. System.out.println(dir.mkdir());
    9. System.out.println(dir.isDirectory());
    10. System.out.println(dir.isFile());
    11. }
    12. }
    13. 运行结果
    14. false
    15. false
    16. false
    17. false
    18. false

    注:mkdir() 的时候,如果中间⽬录不存在,则⽆法创建成功; mkdirs() 可以解决这个问题。

    1. import java.io.File;
    2. import java.io.IOException;
    3. public class Main {
    4. public static void main(String[] args) throws IOException {
    5. File dir = new File("some-parent\\some-dir"); // some-parent 和 so
    6. System.out.println(dir.isDirectory());
    7. System.out.println(dir.isFile());
    8. System.out.println(dir.mkdirs());
    9. System.out.println(dir.isDirectory());
    10. System.out.println(dir.isFile());
    11. }
    12. }
    13. 运行结果
    14. false
    15. false
    16. true
    17. true
    18. false

    1.2.5.观察文件重命名

    1. import java.io.File;
    2. import java.io.IOException;
    3. public class Main {
    4. public static void main(String[] args) throws IOException {
    5. File file = new File("some-file.txt"); // 要求 some-file.txt 得存在
    6. File dest = new File("dest.txt"); // 要求 dest.txt 不存在
    7. System.out.println(file.exists());
    8. System.out.println(dest.exists());
    9. System.out.println(file.renameTo(dest));
    10. System.out.println(file.exists());
    11. System.out.println(dest.exists());
    12. }
    13. }
    14. 运行结果
    15. true
    16. false
    17. true
    18. false
    19. true

    二.InputStream

    2.1方法

    说明

    InputStream 只是⼀个抽象类,要使⽤还需要具体的实现类。关于 InputStream 的实现类有很多,基本可以认为不同的输⼊设备都可以对应⼀个 InputStream 类,我们现在只关⼼从⽂件中读取,所以使⽤ FileInputStream

    2.2FileInputStream

     示例代码1:

    将⽂件完全读完的两种⽅式。相⽐较⽽⾔,后⼀种的 IO 次数更少,性能更好。
    1. import java.io.*;
    2. // 需要先在项⽬⽬录下准备好⼀个 hello.txt 的⽂件,⾥⾯填充 "Hello" 的内容
    3. public class Main {
    4. public static void main(String[] args) throws IOException {
    5. try (InputStream is = new FileInputStream("hello.txt")) {
    6. while (true) {
    7. int b = is.read();
    8. if (b == -1) {
    9. // 代表⽂件已经全部读完
    10. break;
    11. }
    12. System.out.printf("%c", b);
    13. }
    14. }
    15. }
    16. }
    1. import java.io.*;
    2. // 需要先在项⽬⽬录下准备好⼀个 hello.txt 的⽂件,⾥⾯填充 "Hello" 的内容
    3. public class Main {
    4. public static void main(String[] args) throws IOException {
    5. try (InputStream is = new FileInputStream("hello.txt")) {
    6. byte[] buf = new byte[1024];
    7. int len;
    8. while (true) {
    9. len = is.read(buf);
    10. if (len == -1) {
    11. // 代表⽂件已经全部读完
    12. break;
    13. }
    14. for (int i = 0; i < len; i++) {
    15. System.out.printf("%c", buf[i]);
    16. }
    17. }
    18. }
    19. }
    20. }

    示例代码二:

           这⾥我们把⽂件内容中填充中⽂看看,注意,写中⽂的时候使⽤ UTF-8 编码。hello.txt 中填写 "你好中国"
           注意:这⾥我利⽤了这⼏个中⽂的 UTF-8 编码后⻓度刚好是 3 个字节和⻓度不超过 1024 字节的现状,但这种⽅式并不是通⽤的。
    1. import java.io.*;
    2. // 需要先在项⽬⽬录下准备好⼀个 hello.txt 的⽂件,⾥⾯填充 "你好中国" 的内容
    3. public class Main {
    4. public static void main(String[] args) throws IOException {
    5. try (InputStream is = new FileInputStream("hello.txt")) {
    6. byte[] buf = new byte[1024];
    7. int len;
    8. while (true) {
    9. len = is.read(buf);
    10. if (len == -1) {
    11. // 代表⽂件已经全部读完
    12. break;
    13. }
    14. // 每次使⽤ 3 字节进⾏ utf-8 解码,得到中⽂字符
    15. // 利⽤ String 中的构造⽅法完成
    16. // 这个⽅法了解下即可,不是通⽤的解决办法
    17. for (int i = 0; i < len; i += 3) {
    18. String s = new String(buf, i, 3, "UTF-8");
    19. System.out.printf("%s", s);
    20. }
    21. }
    22. }
    23. }
    24. }

    2.3利用Scanner进行字符读取

           上述例⼦中,我们看到了对字符类型直接使⽤ InputStream 进⾏读取是⾮常⿇烦且困难的,所以,我们使⽤⼀种我们之前⽐较熟悉的类来完成该⼯作,就是 Scanner 类。

    示例代码如下:

    1. import java.io.*;
    2. import java.util.*;
    3. // 需要先在项⽬⽬录下准备好⼀个 hello.txt 的⽂件,⾥⾯填充 "你好中国" 的内容
    4. public class Main {
    5. public static void main(String[] args) throws IOException {
    6. try (InputStream is = new FileInputStream("hello.txt")) {
    7. try (Scanner scanner = new Scanner(is, "UTF-8")) {
    8. while (scanner.hasNext()) {
    9. String s = scanner.next();
    10. System.out.print(s);
    11. }
    12. }
    13. }
    14. }
    15. }

    三.OutputStream

    3.1方法

    说明:

    OutputStream 同样只是⼀个抽象类,要使⽤还需要具体的实现类。我们现在还是只关⼼写⼊⽂件
    中,所以使⽤ FileOutputStream

    3.2FileOutputStream

    五个示例代码如下:

    1. import java.io.*;
    2. public class Main {
    3. public static void main(String[] args) throws IOException {
    4. try (OutputStream os = new FileOutputStream("output.txt")) {
    5. os.write('H');
    6. os.write('e');
    7. os.write('l');
    8. os.write('l');
    9. os.write('o');
    10. // 不要忘记 flush
    11. os.flush();
    12. }
    13. }
    14. }
    1. import java.io.*;
    2. public class Main {
    3. public static void main(String[] args) throws IOException {
    4. try (OutputStream os = new FileOutputStream("output.txt")) {
    5. byte[] b = new byte[] {
    6. (byte)'G', (byte)'o', (byte)'o', (byte)'d'
    7. };
    8. os.write(b);
    9. // 不要忘记 flush
    10. os.flush();
    11. }
    12. }
    13. }
    1. import java.io.*;
    2. public class Main {
    3. public static void main(String[] args) throws IOException {
    4. try (OutputStream os = new FileOutputStream("output.txt")) {
    5. byte[] b = new byte[] {
    6. (byte)'G', (byte)'o', (byte)'o', (byte)'d', (byte)'B', (byte)'a'
    7. };
    8. os.write(b, 0, 4);
    9. // 不要忘记 flush
    10. os.flush();
    11. }
    12. }
    13. }
    1. import java.io.*;
    2. public class Main {
    3. public static void main(String[] args) throws IOException {
    4. try (OutputStream os = new FileOutputStream("output.txt")) {
    5. String s = "Nothing";
    6. byte[] b = s.getBytes();
    7. os.write(b);
    8. // 不要忘记 flush
    9. os.flush();
    10. }
    11. }
    12. }
    1. import java.io.*;
    2. public class Main {
    3. public static void main(String[] args) throws IOException {
    4. try (OutputStream os = new FileOutputStream("output.txt")) {
    5. String s = "你好中国";
    6. byte[] b = s.getBytes("utf-8");
    7. os.write(b);
    8. // 不要忘记 flush
    9. os.flush();
    10. }
    11. }
    12. }

    3.3利用PrintWriter找到我们熟系的方法

    上述,我们其实已经完成输出⼯作,但总是有所不⽅便,我们接来下将 OutputStream 处理下,使⽤PrintWriter 类来完成输出,因为PrintWriter 类中提供了我们熟悉的 print/println/printf ⽅法。
    示例代码如下:
    1. OutputStream os = ...;
    2. OutputStreamWriter osWriter = new OutputStreamWriter(os, "utf-8");
    3. PrintWriter writer = new PrintWriter(osWriter);
    4. // 接下来我们就可以⽅便的使⽤ writer 提供的各种⽅法了
    5. writer.print("Hello");
    6. writer.println("你好");
    7. writer.printf("%d: %s\n", 1, "没什么");
    8. // 不要忘记 flush
    9. writer.flush();
    1. import java.io.*;
    2. public class Main {
    3. public static void main(String[] args) throws IOException {
    4. try (OutputStream os = new FileOutputStream("output.txt")) {
    5. try (OutputStreamWriter osWriter = new OutputStreamWriter(os, "UTF-8
    6. try (PrintWriter writer = new PrintWriter(osWriter)) {
    7. writer.println("我是第⼀⾏");
    8. writer.print("我的第⼆⾏\r\n");
    9. writer.printf("%d: 我的第三⾏\r\n", 1 + 1);
    10. writer.flush();
    11. }
    12. }
    13. }
    14. }
    15. }

    尾语

    这篇博客到这里就结束啦,希望可以给大家带来帮助~~

  • 相关阅读:
    一次SpringBoot版本升级,引发的血案
    机器学习实战笔记(二)KNN算法
    C语言之通讯录的实现篇优化版
    PHP 行事准则:allow_url_fopen 与 allow_url_include
    J9数字论:模块化公链能否成为公链新趋势?
    scanf(“%s“, filename);这里的scanf函数中,“,”逗号符号后面什么时候需要用“&”这个符号,什么时候不需要用这个“&”符号?
    Spring Boot后端+Vue前端:打造高效二手车交易系统
    docker 增加cpu线程数
    隐式转换这个概念你听说过没?
    Python绘图系统25:新增8种绘图函数
  • 原文地址:https://blog.csdn.net/weixin_66046886/article/details/136636091