温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java I/O流如何使用

发布时间:2022-08-05 09:56:53 来源:亿速云 阅读:139 作者:iii 栏目:开发技术

本文小编为大家详细介绍“Java I/O流如何使用”,内容详细,步骤清晰,细节处理妥当,希望这篇“Java I/O流如何使用”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

1.java IO包

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

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

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

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

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

Java I/O流如何使用

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

Java I/O流如何使用

2.创建文件

方式一:

/**
 * 创建文件,第一种方式
 */
@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);
    }
}

第二种方式:

/**
 * 创建文件,第二种方式
 */
@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);
    }
}

第三种方式:

/**
 * 创建文件,第三种方式
 */
@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.获取文件信息

示例代码:

/**
 * 获取文件信息
 */
@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.目录操作

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

// 判断指定目标是否存在,如果存在就删除
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("文件不存在!");
}

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

// 判断目录是否存在,如果存在即删除
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("目录不存在!");
}

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

// 判断指定目录是否存在,不存在就创建目录
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 对象字节输入流

Java I/O流如何使用

FileInputStream

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

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

/**
 * 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数组的方式读取,这使得可以读取中文,并且有效的提升读取效率:

/**
 * 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

Java I/O流如何使用

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

/**
 * 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构造器无法实现向文件中追加内容,只能进行覆盖,我们可以在初始化对象的时候这样解决:

fileOutputStream = new FileOutputStream(filePath,true);

7.模拟文件拷贝

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

/**
 * 文件拷贝
 * 思路:
 * 创建文件的输入流,将文件读取到程序
 * 创建文件的输出流,将读取到的文件数据写入到指定的文件
 */
@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用于从文件中读取数据

示例:

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用于写数据到文件中:

示例:

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,记得关闭文件或者刷新流!

读到这里,这篇“Java I/O流如何使用”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI