java读取文件常见方式

FileInputStream (读字节)

这适用于二进制文件或非文本文件
第一种:(不能读文本)

 public static void main(String[] args) throws IOException {
     FileInputStream fis = new FileInputStream(new File("D:/t.txt"));
     int data;
     while ((data = fis.read()) != -1) {//data是一个数字
         System.out.println((char) data);//将当前字节转换为字符
     }
 }

第二种:(可以读文本)

 public static void main(String[] args) throws FileNotFoundException {
     FileInputStream fis = new FileInputStream(new File("D:/t.txt"));
     Scanner scanner = new Scanner(fis);
     while (scanner.hasNext()) {
         System.out.println(scanner.nextLine());
     }
 }

为什么可以读取文本呢?nextLine()方法返回字符串

FileReader 和 BufferedReader(读字符)

第一种:

public static void main(String[] args) throws IOException {
      FileReader fileReader = new FileReader(new File("D:/t.txt"));
      int data;
      while ((data = fileReader.read()) != -1) {
          System.out.print((char) data);
      }
  }

第二种:
BufferedReader 内部维护了一个缓冲区,可以一次读取多个字符并缓存在内存中。相比于每次读取一个字符的 FileReader,使用 BufferedReader 可以减少系统调用次数,提高读取效率。

 public static void main(String[] args) throws IOException {
     FileReader fileReader = new FileReader(new File("D:/t.txt"));
     BufferedReader bufferedReader = new BufferedReader(fileReader);
     String line;
     while ((line = bufferedReader.readLine()) != null) {
         System.out.println(line);
     }
 }

Files

import java.nio.file.Files;用于文件操作的 NIO(New I/O)包的一部分
第一种:(读取小文件)

 public static void main(String[] args) throws IOException {
     List<String> list = Files.readAllLines(Path.of("D:/t.txt"));
     //Lambda表达式
     list.forEach(line-> System.out.println(line));
 }

Files 类提供的 readAllLines(Path) 方法通常适用于读取小型文本文件,因为它一次性将整个文件的内容加载到内存中,然后存储在一个字符串列表中。如果文件非常大,加载整个文件内容可能会导致内存溢出的风险。

对于大文件,更适合使用基于 NIO 的方法来进行读取,这样可以有效地处理大量数据而不会耗尽内存。你可以使用 Files.newBufferedReader(Path) 方法结合 BufferedReader 来逐行读取大文件的内容,示例代码如下:
第二种:(读取大文件)

 public static void main(String[] args) throws IOException {
     BufferedReader reader = Files.newBufferedReader(Path.of("D:/t.txt"));
     String line;
     while ((line = reader.readLine()) != null) {
         //处理数据 这里打印输出
         System.out.println(line);
     }
 }

FileUtils

import org.apache.commons.io.FileUtils;
Apache Commons IO 库是 Apache 软件基金会的一个开源项目,提供了许多用于简化 I/O 操作的实用工具类。其中,FileUtils 类是该库中的一个工具类,提供了各种用于文件操作的静态方法,例如读取文件、写入文件、复制文件、删除文件等。

第一种:(读取小文件)

 public static void main(String[] args) throws IOException {
 	 //读取小文件 	 
     String s = FileUtils.readFileToString(new File("D:/t.txt"));
     System.out.println(s);
 }

第二种:(读取大文件)

 public static void main(String[] args) throws IOException {
     LineIterator lineIterator = FileUtils.lineIterator(new File("D:/t.txt"));
     while (lineIterator.hasNext()) {
         System.out.println(lineIterator.nextLine());
     }
 }

FileChannel

 public static void main(String[] args) throws IOException {
     RandomAccessFile file = new RandomAccessFile("D:/t.txt", "r");
     // 获取文件的 FileChannel
     FileChannel channel = file.getChannel();
     // 创建 ByteBuffer,用于存储从 FileChannel 中读取的数据
     ByteBuffer buffer = ByteBuffer.allocate(1024);
     // 从 FileChannel 中读取数据到 ByteBuffer 中
     int read = channel.read(buffer);
     while (read != -1) {
         // 切换 buffer 为读模式
         buffer.flip();
         while (buffer.hasRemaining()) {
             System.out.print((char) buffer.get());
         }
         // 清空buffer为下一次读取做准备
         buffer.clear();
         // 继续从FileChannel中读取数据到buffer
         read = channel.read(buffer);
     }
     // 关闭FileChannel和文件
     channel.close();
     file.close();
 }

小结

FileInputStream:FileInputStream 是 Java IO 包中用于读取文件的类之一。它可以逐字节地读取文件内容,并且通常结合其他类,如 InputStreamReader 或 BufferedInputStream 来提高效率。
BufferedReader:BufferedReader 是 Java IO 包中的一个类,它提供了缓冲区功能,可以一次读取一行文本。通常与 FileReader 结合使用,用于逐行读取文本文件。
Files:Files 类是 Java NIO 包中提供的工具类,用于执行各种文件操作。它包含了读取文件内容的方法,如 readAllLines(Path),可以一次性读取整个文件的内容并返回一个字符串列表。
FileUtils:FileUtils 是 Apache Commons IO 库中的一个工具类,提供了各种用于文件操作的静态方法。其中的 readFileToString(File) 方法可以方便地读取文件内容并返回一个字符串。
FileChannel:FileChannel 是 Java NIO 包中的一个类,用于执行文件的低级别 I/O 操作。它提供了更底层的文件读取和写入功能,并支持非阻塞 I/O、内存映射文件等高级特性。

选择哪种方法取决于具体的需求和偏好。如果需要简单地读取整个文件的内容,可以使用 Files 或 FileUtils 提供的方法。如果需要逐行读取文本文件,可以使用 BufferedReader。如果需要更底层的、灵活的文件读取操作,则可以使用 FileChannel。

  • 22
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中,可以使用File类和InputStream、Reader等类来读取文件。下面分别介绍几种常见读取文件方式: 1. 使用FileInputStream读取文件: ``` File file = new File("file_path"); try (InputStream input = new FileInputStream(file)) { byte[] buffer = new byte[1024]; int n = -1; while ((n = input.read(buffer)) != -1) { // 处理读取到的数据 } } catch (IOException e) { e.printStackTrace(); } ``` 上述代码中,通过创建File对象来指定要读取文件路径,然后使用FileInputStream来读取文件数据。在读取过程中,使用一个字节数组作为缓冲区,每次读取一定大小的数据,直到读取完整个文件。 2. 使用FileReader读取文本文件: ``` File file = new File("file_path"); try (Reader reader = new FileReader(file)) { char[] buffer = new char[1024]; int n = -1; while ((n = reader.read(buffer)) != -1) { // 处理读取到的数据 } } catch (IOException e) { e.printStackTrace(); } ``` 上述代码中,通过创建File对象来指定要读取的文本文件路径,然后使用FileReader来读取文件数据。在读取过程中,使用一个字符数组作为缓冲区,每次读取一定大小的数据,直到读取完整个文件。 3. 使用Scanner读取文本文件: ``` File file = new File("file_path"); try (Scanner scanner = new Scanner(file)) { while (scanner.hasNextLine()) { String line = scanner.nextLine(); // 处理读取到的行数据 } } catch (IOException e) { e.printStackTrace(); } ``` 上述代码中,通过创建File对象来指定要读取的文本文件路径,然后使用Scanner来读取文件数据。在读取过程中,使用Scanner的nextLine()方法逐行读取文件数据,直到读取完整个文件。 需要注意的是,以上代码中使用了try-with-resources语句来自动关闭文件流,确保资源得到释放。同时,需要捕获可能抛出的IOException异常。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值