java读取文件的几种方法

1 使用FileInputStream

package file.io.readfile;

import java.io.*;

public class FileInputStreamTest {

    public static void main(String[] args) throws Exception {
//        testInputStream();
//        testInputStream2();
        testInputStream3();
//        testInputStreamReader();
    }

    public static void testInputStream() throws Exception {
        String path = "E:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";

        long length = new File(path).length();
        byte[] buffer = new byte[(int)length];

        FileInputStream fileInputStream = new FileInputStream(path);
        int unread = (int)length;
        //  如果是大文件,需要多次读,这里简单地一次读取文件全部内容
        // 多次读取可以采用的方式:
        // 分配一个大内存,每次读取通过指定偏移以及读取数据大小来移动偏移
        // 全部数据使用一个大内存,分配一个小内存来存储每次读取的数据,然后把每次读取的数据复制到大内存
        try (BufferedInputStream bf = new BufferedInputStream(fileInputStream)) {
            bf.read(buffer, 0, unread);
        }

        System.out.println(new String(buffer));
    }

    public static void testInputStream2() throws Exception {
        String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";

        long length = new File(path).length();
        byte[] buffer = new byte[(int)length];

        FileInputStream fileInputStream = new FileInputStream(path);
        int unread = (int)length;
        //  如果是大文件,需要多次读,这里简单地一次读取文件全部内容
        // 多次读取可以采用的方式:
        // 分配一个大内存,每次读取通过指定偏移以及读取数据大小来移动偏移
        // 全部数据使用一个大内存,分配一个小内存来存储每次读取的数据,然后把每次读取的数据复制到大内存
        int n;
        int pos = 0;
        try (BufferedInputStream bf = new BufferedInputStream(fileInputStream)) {
            while((n = bf.read(buffer, pos, unread)) > 0) {
                pos += n;
                unread = unread - n;
            }
        }

        System.out.println(new String(buffer));
    }

    public static void testInputStream3() throws Exception {
        String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";

        long length = new File(path).length();
        byte[] buffer = new byte[(int)length];

        FileInputStream fileInputStream = new FileInputStream(path);
        int unread = (int)length;
        //  如果是大文件,需要多次读,这里简单地一次读取文件全部内容
        // 多次读取可以采用的方式:
        // 分配一个大内存,每次读取通过指定偏移以及读取数据大小来移动偏移
        // 全部数据使用一个大内存,分配一个小内存来存储每次读取的数据,然后把每次读取的数据复制到大内存
        int n;
        int pos = 0;

        byte[] readBuf = new byte[1024];
        try (BufferedInputStream bf = new BufferedInputStream(fileInputStream)) {
            while((n = bf.read(readBuf)) > 0) {
                int size = Math.min(n, unread);
                System.arraycopy(readBuf, 0, buffer, pos, size);
                pos += n;
                unread = unread - n;
                // 考虑文件增大,比刚开始大小大的情况。
                if (unread <= 0) {
                    break;
                }
            }
        }

        System.out.println(new String(buffer));
    }

    /**
     * 使用字符流
     * @throws Exception
     */
    public static void testInputStreamReader() throws Exception {
        String path = "E:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";

        long length = new File(path).length();
        byte[] buffer = new byte[(int)length];

        FileInputStream fileInputStream = new FileInputStream(path);
        int unread = (int)length;
        //  按行读取,读到的每一行不包括末尾的换行符
        try (BufferedReader bf = new BufferedReader(new InputStreamReader(fileInputStream))) {
            String line;
            while ((line = bf.readLine()) != null) {
                System.out.println(line);
            }
        }

        System.out.println(new String(buffer));
    }

}

1.1 小结

1)FileInputStream可以直接读取字节流,也可以转换成字符流读取。
2)可以读取大文件。
3)需要使用者是否资源。
4)是传统经典使用方式。

2 使用FileReader

package file.io.readfile;

import java.io.BufferedReader;
import java.io.FileReader;

public class FileReaderTest {
    public static void main(String[] args) throws Exception {
        testReader();
    }

    public static void testReader() throws Exception {
        String path = "E:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";

        // 使用FileReader不能指定文件编码
        try (BufferedReader bf = new BufferedReader(new FileReader(path))) {
            String line;
            while ((line = bf.readLine()) != null) {
                System.out.println(line);
            }
        }
    }

}

2.1 小结

字符流方式读取文件,适合按行读取情况。

3 使用RandomAccessFile

package file.io.readfile;

import java.io.RandomAccessFile;

/**
 * @description:
 * @author: LiYuan
 * @date: 2024/7/24 9:51
 */
public class RandomAccessFileTest {

    public static void main(String[] args) throws Exception {
        test1();
    }

    public static void test1() throws Exception {
        String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
        try (RandomAccessFile randomAccessFile = new RandomAccessFile(path, "rw")) {
            // 获取文件大小
            // 另一个获取文件大小的方法是new File(path).length()
            // 通过打开文件流来获取文件大小的方法更好,原因有:
            // 避免两次打开文件;
            // 避免并发问题导致获取文件大小错误
            long length = randomAccessFile.length();
            byte[] buffer = new byte[(int)length];
            // 可以使用readLine分行读取
            // 如果是大文件,需要多次读取
            // 严格来说,需要判断是否读取完了整个文件
            randomAccessFile.read(buffer);
            System.out.println(new String(buffer));
        }
    }

}

3.1 小结

1)可以读取大文件
2)可以随机读取

4 使用Scanner

package file.io.readfile;

import java.io.FileReader;
import java.util.Scanner;

/**
 * @description:
 * @author: LiYuan
 * @date: 2024/7/24 10:48
 */
public class ScannerTest {
    public static void main(String[] args) throws Exception {
//        test1();
//        test2();
//        test3();
        test4();
    }

    public static void test1() throws Exception {
        String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
        try (Scanner scanner = new Scanner(new FileReader(path))) {
            // 按空格分隔
            while (scanner.hasNext()) {
                String line = scanner.next();
                System.out.println(line);
            }
        }
    }

    public static void test2() throws Exception {
        String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
        try (Scanner scanner = new Scanner(new FileReader(path))) {
            // 按空格分隔
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
        }
    }

    public static void test3() throws Exception {
        String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
        try (Scanner scanner = new Scanner(new FileReader(path))) {
            // 指定分隔符
            scanner.useDelimiter("\n");
            while (scanner.hasNext()) {
                String line = scanner.next();
                System.out.println(line);
            }
        }
    }

    public static void test4() throws Exception {
        String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
        try (Scanner scanner = new Scanner(new FileReader(path))) {
            // 指定分隔符
            scanner.useDelimiter(" ");
            while (scanner.hasNext()) {
                String word = scanner.next();
                System.out.println(word);
            }
        }
    }
    
}

4.1 小结
1)适合按行、按分隔符读取字符文件

5 使用java.nio.file.Files

package file.io.readfile;



import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FilesTest {
    public static void main(String[] args) throws Exception {
//        test1();
//        test2();
//        test3();
//        test4();
//        test5();
        test6();
    }

    public static void test1() throws Exception {
        String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
        // 可以指定编码
//        Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8);
        List<String> lines = Files.readAllLines(Paths.get(path));

        for (String line : lines) {
            System.out.println(line);
        }
    }

    public static void test2() throws Exception {
        String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
        // 可以指定编码
//        Files.newBufferedReader(Paths.get(path), StandardCharsets.UTF_8);
        try (BufferedReader bf = Files.newBufferedReader(Paths.get(path))) {
            String line;
            while ((line = bf.readLine()) != null) {
                System.out.println(line);
            }
        }
    }

    public static void test3() throws Exception {
        String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
        // 可以指定编码
//        Files.lines(Paths.get(path), StandardCharsets.UTF_8);
        Stream<String>  stringStream = Files.lines(Paths.get(path));
        stringStream.forEach(line -> {
            System.out.println(line);
        });
    }

    public static void test4() throws Exception {
        String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
        // 可以指定编码
//        Files.lines(Paths.get(path), StandardCharsets.UTF_8);
        Stream<String>  stringStream = Files.lines(Paths.get(path));
        // 保证处理顺序
        stringStream.forEachOrdered(line -> {
            System.out.println(line);
        });
    }

    public static void test5() throws Exception {
        String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
        // 可以指定编码
//        Files.lines(Paths.get(path), StandardCharsets.UTF_8);
        Stream<String>  stringStream = Files.lines(Paths.get(path));
        List<String> list = stringStream.collect(Collectors.toList());
        for (String line : list) {
            System.out.println(line);
        }
    }

    /**
     * 一次性读取整个文件
     * @throws Exception
     */
    public static void test6() throws Exception {
        String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
        // 可以指定编码
//        Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8);
        byte[] buffer = Files.readAllBytes(Paths.get(path));
        // jdk11提供方法
//        Files.readString(Paths.get(path));
        System.out.println(new String(buffer));
    }
}

5.1 小结

1)适合按行读取文件
2)一次性读取整个文件,得到字节数组

6 使用com.google.common.io.Files

package file.io.readfile;


import com.google.common.io.Files;

import java.io.BufferedReader;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @description:
 * @author: LiYuan
 * @date: 2024/7/24 11:34
 */
public class FileTest2 {
    public static void main(String[] args) throws Exception {
//        test1();
        test2();
    }

    public static void test1() throws Exception {
        String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
        List<String> lines = Files.readLines(new File(path), StandardCharsets.UTF_8);
        for (String line : lines) {
            System.out.println(line);
        }
    }

    public static void test2() throws Exception {
        String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
        try (BufferedReader bf = Files.newReader(new File(path), StandardCharsets.UTF_8)) {
            String line;
            while ((line = bf.readLine()) != null) {
                System.out.println(line);
            }

        }
    }
}

6.1 小结

1)适合按行读取文件

7 使用org.apache.commons.io.FileUtils

package file.io.readfile;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @description:
 * @author: LiYuan
 * @date: 2024/7/24 11:50
 */
public class FileUtilsTest {
    public static void main(String[] args) throws Exception {
//        test1();
//        test2();
        test3();
    }

    public static void test1() throws Exception {
        String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
        // 用编码字面值指定编码,例如
        // List<String> lines =  FileUtils.readLines(new File(path), “UTF-8");
        // 或者使用默认编码
        // List<String> lines =  FileUtils.readLines(new File(path))
        List<String> lines =  FileUtils.readLines(new File(path), StandardCharsets.UTF_8);
        for (String line : lines) {
            System.out.println(line);
        }
    }


    public static void test2() throws Exception {
        String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
        // 用编码字面值指定编码,例如
        // FileUtils.readFileToString(new File(path), “UTF-8");
        // 或者使用默认编码
        // FileUtils.readFileToString(new File(path))
        String content = FileUtils.readFileToString(new File(path), StandardCharsets.UTF_8);
        System.out.println(content);
    }

    /**
     * 读取整个文件到字节数组
     * @throws Exception
     */
    public static void test3() throws Exception {
        String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
        byte[] buffer = FileUtils.readFileToByteArray(new File(path));
        System.out.println(new String(buffer));
    }
}

7.1 小结

1)适合按行读取文件
2)一次性读取整个文件,得到字节数组或字符串。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ly21st

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值