广告位联系
返回顶部
分享到

Java I/O流使用示例介绍

java 来源:互联网 作者:酷站 发布时间:2022-08-04 18:31:52 人浏览
摘要

1.java IO包 Java.io 包几乎包含了所有操作输入、输出需要的类。所有这些流类代表了输入源和输出目标。 Java.io 包中的流支持很多种格式,比如:基本类型、对象、本地化字符集等等。

1.java IO包

Java.io 包几乎包含了所有操作输入、输出需要的类。所有这些流类代表了输入源和输出目标。

Java.io 包中的流支持很多种格式,比如:基本类型、对象、本地化字符集等等。

一个流可以理解为一个数据的序列。输入流表示从一个源读取数据,输出流表示向一个目标写数据。

文件依靠流进行传输,就像快递依托于快递员进行分发

Java 为 I/O 提供了强大的而灵活的支持,使其更广泛地应用到文件传输和网络编程中。

下图是一个描述输入流和输出流的类层次图。

 

2.创建文件

方式一:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

/**

 * 创建文件,第一种方式

 */

@Test

public void createFile01() {

    String filePath = "D://1.txt";

    File file = new File(filePath);

    try {

        file.createNewFile();

        System.out.println("文件创建成功!");

    } catch (IOException e) {

        throw new RuntimeException(e);

    }

}

第二种方式:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

/**

 * 创建文件,第二种方式

 */

@Test

public void createFile02() {

    File parentFile = new File("D:\");

    String fileName = "news.txt";

    File file = new File(parentFile, fileName);

    try {

        file.createNewFile();

        System.out.println("文件创建成功!");

    } catch (IOException e) {

        throw new RuntimeException(e);

    }

}

第三种方式:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

/**

 * 创建文件,第三种方式

 */

@Test

public void createFile03() {

    String parentPath = "D:\";

    String fileName = "my.txt";

    File file = new File(parentPath, fileName);

    try {

        file.createNewFile();

        System.out.println("文件创建成功!");

    } catch (IOException e) {

        throw new RuntimeException(e);

    }

}

 

3.获取文件信息

示例代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

/**

 * 获取文件信息

 */

@Test

public void info() {

    // 创建文件对象

    File file = new File("D:\news.txt");

    // 获取文件名字

    System.out.println(file.getName());

    // 获取文件路径

    System.out.println(file.getAbsolutePath());

    // 获取文件父亲目录

    System.out.println(file.getParent());

    // 获取文件大小(字节)

    System.out.println(file.length());

    // 文件是否存在

    System.out.println(file.exists());

    // 是不是一个文件

    System.out.println(file.isFile());

    // 是不是一个目录

    System.out.println(file.isDirectory());

}

 

4.目录操作

案例一:判断指定目标是否存在,如果存在就删除

1

2

3

4

5

6

7

8

9

10

11

12

// 判断指定目标是否存在,如果存在就删除

String filePath = "D:\news.txt";

File file = new File(filePath);

if (file.exists()) {

    if (file.delete()) {

        System.out.println("删除成功!");

    } else {

        System.out.println("删除失败!");

    }

} else {

    System.out.println("文件不存在!");

}

案例二:判断目录是否存在,如果存在即删除

1

2

3

4

5

6

7

8

9

10

11

12

// 判断目录是否存在,如果存在即删除

String dirPath = "D:\demo";

File file1 = new File(dirPath);

if (file1.exists()) {

    if (file1.delete()) {

        System.out.println("删除成功!");

    } else {

        System.out.println("删除失败!");

    }

} else {

    System.out.println("目录不存在!");

}

案例三:判断指定目录是否存在,不存在就创建目录

1

2

3

4

5

6

7

8

9

10

11

12

// 判断指定目录是否存在,不存在就创建目录

String persondir = "D:\demo\a\b\c";

File file2 = new File(persondir);

if (file2.exists()) {

    System.out.println("该目录存在!");

} else {

    if (file2.mkdirs()) {

        System.out.println("目录创建成功!");

    } else {

        System.out.println("目录创建失败!");

    }

}

注意:创建多级目录,使用mkdirs,创建一级目录使用mkdir

 

5.字节输入流InputStream

InputStream抽象类是所有类字节输入流的超类

  • FileInputStream 文件输入流
  • BufferedInputStream 缓冲字节输入流
  • ObjectInputStream 对象字节输入流

FileInputStream

文件输入流,从文件中读取数据,示例代码:

单个字节的读取,效率较低:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

/**

 * read()读文件

 */

@Test

public void readFile01() throws IOException {

    String filePath = "D:\hacker.txt";

    int readData = 0;

    FileInputStream fileInputStream = null;

    try {

        fileInputStream = new FileInputStream(filePath);

        // 读文件,一个字符一个字符读取,返回字符的ASCII码,文件尾部返回-1

        while ((readData = fileInputStream.read()) != -1) {

            System.out.print((char)readData);

        }

    } catch (IOException e) {

        throw new RuntimeException(e);

    } finally {

        // 关闭流资源

        fileInputStream.close();

    }

}

注意:使用字节流的方式,无法读取文件中的中文字符,如需读取中文字符,最好使用字符流的方式

使用byte数组的方式读取,这使得可以读取中文,并且有效的提升读取效率:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

/**

 * read(byte[] b)读文件

 * 支持多字节读取,提升效率

 */

@Test

public void readFile02() throws IOException {

    String filePath = "D:\hacker.txt";

    int readData = 0;

    int readLen = 0;

    // 字节数组

    byte[] bytes = new byte[8]; // 一次最多读取8个字节

 

    FileInputStream fileInputStream = null;

    try {

        fileInputStream = new FileInputStream(filePath);

        // 读文件,从字节数组中直接读取

        // 如果读取正常,返回实际读取的字节数

        while ((readLen = fileInputStream.read(bytes)) != -1) {

            System.out.print(new String(bytes, 0, readLen));

        }

    } catch (IOException e) {

        throw new RuntimeException(e);

    } finally {

        // 关闭流资源

        fileInputStream.close();

    }

}

 

6.字节输出流FileOutputStream

使用示例:(向hacker.txt文件中加入数据)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

/**

 * FileOutputStream数据写入文件

 * 如果该文件不存在,则创建该文件

 */

@Test

public void writeFile() throws IOException {

    String filePath = "D:\hacker.txt";

    FileOutputStream fileOutputStream = null;

    try {

        fileOutputStream = new FileOutputStream(filePath);

        // 写入一个字节

        // fileOutputStream.write('G');

        // 写入一个字符串

        String s = "hello hacker!";

        // fileOutputStream.write(s.getBytes());

        // 写入字符串指定范围的字符

        fileOutputStream.write(s.getBytes(),0,3);

    } catch (FileNotFoundException e) {

        throw new RuntimeException(e);

    } finally {

        assert fileOutputStream != null;

        fileOutputStream.close();

    }

}

我们发现,使用这样的FileOutputStream构造器无法实现向文件中追加内容,只能进行覆盖,我们可以在初始化对象的时候这样解决:

1

fileOutputStream = new FileOutputStream(filePath,true);

 

7.模拟文件拷贝

我们可以结合字节输入和输出流模拟一个文件拷贝的程序:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

/**

 * 文件拷贝

 * 思路:

 * 创建文件的输入流,将文件读取到程序

 * 创建文件的输出流,将读取到的文件数据写入到指定的文件

 */

@Test

public void Copy() throws IOException {

    String srcFilePath = "D:\hacker.txt";

    String destFilePath = "D:\hello.txt";

    FileInputStream fileInputStream = null;

    FileOutputStream fileOutputStream = null;

    try {

        fileInputStream = new FileInputStream(srcFilePath);

        fileOutputStream = new FileOutputStream(destFilePath);

        // 定义字节数组,提高效率

        byte[] buf = new byte[1024];

        int readLen = 0;

        while ((readLen = fileInputStream.read(buf)) != -1) {

            // 边读边写

            fileOutputStream.write(buf, 0, readLen);

        }

        System.out.println("拷贝成功!");

    } catch (IOException e) {

        throw new RuntimeException(e);

    } finally {

        if (fileInputStream != null){

            fileInputStream.close();

        }

        if (fileOutputStream != null) {

            fileOutputStream.close();

        }

    }

}

 

8.字符输入流FileReader

字符输入流FileReader用于从文件中读取数据

示例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

import java.io.FileWriter;

import java.io.IOException;

 

/**

 * 字符输出流

 */

public class FileWriteTest {

    public static void main(String[] args) throws IOException {

        String filePath = "D:\hacker.txt";

        // 创建对象

        FileWriter fileWriter = null;

        try {

            char[] chars = {'a', 'b', 'c'};

            fileWriter = new FileWriter(filePath, true);

            // 写入单个字符

            // fileWriter.write('H');

            // 写入字符数组

            // fileWriter.write(chars);

            // 指定数组的范围写入

            // fileWriter.write(chars, 0, 2);

            // 写入字符串

            // fileWriter.write("解放军万岁!");

            // 指定字符串的写入范围

            fileWriter.write("hacker club", 0, 5);

        } catch (IOException e) {

            throw new RuntimeException(e);

        } finally {

            // FileWriter是需要强制关闭文件或刷新流的,否则数据会保存失败

            fileWriter.close();

        }

    }

}

 

9.字符输出流FileWriter

字符输出流FileWrite用于写数据到文件中:

示例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

import java.io.FileWriter;

import java.io.IOException;

 

/**

 * 字符输出流

 */

public class FileWriteTest {

    public static void main(String[] args) throws IOException {

        String filePath = "D:\hacker.txt";

        // 创建对象

        FileWriter fileWriter = null;

        try {

            char[] chars = {'a', 'b', 'c'};

            fileWriter = new FileWriter(filePath, true);

            // 写入单个字符

            // fileWriter.write('H');

            // 写入字符数组

            // fileWriter.write(chars);

            // 指定数组的范围写入

            // fileWriter.write(chars, 0, 2);

            // 写入字符串

            // fileWriter.write("解放军万岁!");

            // 指定字符串的写入范围

            fileWriter.write("hacker club", 0, 5);

        } catch (IOException e) {

            throw new RuntimeException(e);

        } finally {

            // FileWriter是需要强制关闭文件或刷新流的,否则数据会保存失败

            fileWriter.close();

        }

    }

}

使用FileWriter,记得关闭文件或者刷新流!


版权声明 : 本文内容来源于互联网或用户自行发布贡献,该文观点仅代表原作者本人。本站仅提供信息存储空间服务和不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权, 违法违规的内容, 请发送邮件至2530232025#qq.cn(#换@)举报,一经查实,本站将立刻删除。
原文链接 : https://blog.csdn.net/Gherbirthday0916/article/details/126124224
相关文章
  • SpringBoot自定义错误处理逻辑介绍

    SpringBoot自定义错误处理逻辑介绍
    1. 自定义错误页面 将自定义错误页面放在 templates 的 error 文件夹下,SpringBoot 精确匹配错误信息,使用 4xx.html 或者 5xx.html 页面可以打印错误
  • Java实现手写一个线程池的代码

    Java实现手写一个线程池的代码
    线程池技术想必大家都不陌生把,相信在平时的工作中没有少用,而且这也是面试频率非常高的一个知识点,那么大家知道它的实现原理和
  • Java实现断点续传功能的代码

    Java实现断点续传功能的代码
    题目实现:网络资源的断点续传功能。 二、解题思路 获取要下载的资源网址 显示网络资源的大小 上次读取到的字节位置以及未读取的字节
  • 你可知HashMap为什么是线程不安全的
    HashMap 的线程不安全 HashMap 的线程不安全主要体现在下面两个方面 在 jdk 1.7 中,当并发执行扩容操作时会造成环形链和数据丢失的情况 在
  • ArrayList的动态扩容机制的介绍

    ArrayList的动态扩容机制的介绍
    对于 ArrayList 的动态扩容机制想必大家都听说过,之前的文章中也谈到过,不过由于时间久远,早已忘却。 所以利用这篇文章做做笔记,加
  • JVM基础之字节码的增强技术介绍

    JVM基础之字节码的增强技术介绍
    字节码增强技术 在上文中,着重介绍了字节码的结构,这为我们了解字节码增强技术的实现打下了基础。字节码增强技术就是一类对现有字
  • Java中的字节码增强技术

    Java中的字节码增强技术
    1.字节码增强技术 字节码增强技术就是一类对现有字节码进行修改或者动态生成全新字节码文件的技术。 参考地址 2.常见技术 技术分类 类
  • Redis BloomFilter布隆过滤器原理与实现

    Redis BloomFilter布隆过滤器原理与实现
    Bloom Filter 概念 布隆过滤器(英语:Bloom Filter)是1970年由一个叫布隆的小伙子提出的。它实际上是一个很长的二进制向量和一系列随机映射
  • Java C++算法题解leetcode801使序列递增的最小交换次

    Java C++算法题解leetcode801使序列递增的最小交换次
    题目要求 思路:状态机DP 实现一:状态机 Java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class Solution { public int minSwap(int[] nums1, int[] nums2) { int n
  • Mybatis结果集映射与生命周期介绍

    Mybatis结果集映射与生命周期介绍
    一、ResultMap结果集映射 1、设计思想 对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了 2、resultMap的应用场
  • 本站所有内容来源于互联网或用户自行发布,本站仅提供信息存储空间服务,不拥有版权,不承担法律责任。如有侵犯您的权益,请您联系站长处理!
  • Copyright © 2017-2022 F11.CN All Rights Reserved. F11站长开发者网 版权所有 | 苏ICP备2022031554号-1 | 51LA统计