【Java基础——22 文件相关】

在 Java 中,File 类是用于表示文件和目录路径名的抽象表示。File 类提供了一些方法来操作文件和目录,包括创建、删除、检查文件属性等。下面是 File 类的一些详细介绍,包括常见方法和使用示例。

File 类的常见方法

构造方法
  • File(String pathname):根据指定的路径名字符串创建一个新的 File 实例。
  • File(String parent, String child):根据父路径名字符串和子路径名字符串创建一个新的 File 实例。
  • File(File parent, String child):根据父抽象路径名和子路径名字符串创建一个新的 File 实例。
文件属性方法
  • boolean exists():测试文件或目录是否存在。
  • boolean isFile():测试此抽象路径名表示的文件是否是一个标准文件。
  • boolean isDirectory():测试此抽象路径名表示的文件是否是一个目录。
  • boolean canRead():测试应用程序是否可以读取此抽象路径名表示的文件。
  • boolean canWrite():测试应用程序是否可以修改此抽象路径名表示的文件。
  • boolean canExecute():测试应用程序是否可以执行此抽象路径名表示的文件。
  • long length():返回此抽象路径名表示的文件的长度。
文件操作方法
  • boolean createNewFile():当且仅当具有该名称的文件尚不存在时,创建一个新的空文件。
  • boolean delete():删除此抽象路径名表示的文件或目录。
  • boolean mkdir():创建此抽象路径名指定的目录。
  • boolean mkdirs():创建此抽象路径名指定的目录,包括任何必需但不存在的父目录。
  • boolean renameTo(File dest):重命名此抽象路径名表示的文件。
文件路径方法
  • String getPath():将此抽象路径名转换为路径名字符串。
  • String getAbsolutePath():返回此抽象路径名的绝对路径名字符串。
  • String getCanonicalPath():返回此抽象路径名的规范路径名字符串。
  • File getParentFile():返回此抽象路径名的父路径名的抽象路径名。
目录操作方法
  • String[] list():返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中的文件和目录。
  • File[] listFiles():返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件。

1. 使用 BufferedReader 逐行读取

BufferedReader 提供了高效的方法逐行读取文件,这对于处理大文件非常有用。

工作机制BufferedReader 内部维护一个缓冲区,每次从文件中读取一块数据填充缓冲区。readLine 方法从缓冲区中读取一行数据,当缓冲区空时,再次从文件中读取数据填充缓冲区。

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

public class ReadLargeFile {
    public static void main(String[] args) {
        String filePath = "path/to/largefile.txt";
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                // 处理每一行数据
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. 使用 FileInputStreamBufferedInputStream

FileInputStreamBufferedInputStream 允许逐字节或逐块读取文件。

工作机制BufferedInputStream 也是通过缓冲区机制来优化文件读取,每次从文件中读取一块数据到缓冲区,read 方法则从缓冲区中读取数据。当缓冲区空时,再次从文件中读取数据填充缓冲区。

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class ReadLargeFile {
    public static void main(String[] args) {
        String filePath = "path/to/largefile.txt";
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath))) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = bis.read(buffer)) != -1) {
                // 处理读取的数据
                System.out.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. 使用 RandomAccessFile

RandomAccessFile 允许读取文件的特定部分,这对于需要从文件中间读取数据非常有用。

工作机制RandomAccessFile 可以通过文件指针随机访问文件中的任何位置。通过 read 方法分块读取文件内容,而不是一次性读取整个文件。

import java.io.IOException;
import java.io.RandomAccessFile;

public class ReadLargeFile {
    public static void main(String[] args) {
        String filePath = "path/to/largefile.txt";
        try (RandomAccessFile raf = new RandomAccessFile(filePath, "r")) {
            long fileLength = raf.length();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = raf.read(buffer)) != -1) {
                // 处理读取的数据
                System.out.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4. 使用 java.nio 包中的 FilesPaths

java.nio 提供了一些高级的 I/O 操作,可以更高效地读取大文件。

工作机制Files.lines 方法会返回一个流(Stream),该流会懒加载文件内容,即在处理每一行时才从文件中读取数据。这种方式避免了将整个文件一次性加载到内存中。

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class ReadLargeFile {
    public static void main(String[] args) {
        String filePath = "path/to/largefile.txt";
        try (Stream<String> stream = Files.lines(Paths.get(filePath))) {
            stream.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

5. 文件过滤器

使用 FileFilterFilenameFilter 接口来过滤文件列表:

import java.io.File;
import java.io.FileFilter;

public class FileFilterExample {
    public static void main(String[] args) {
        File dir = new File("exampleDir");

        // 使用匿名类实现 FileFilter 接口
        FileFilter fileFilter = new FileFilter() {
            public boolean accept(File file) {
                return file.isFile() && file.getName().endsWith(".txt");
            }
        };

        File[] files = dir.listFiles(fileFilter);
        if (files != null) {
            System.out.println("Filtered files:");
            for (File file : files) {
                System.out.println(file.getName());
            }
        }
    }
}

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值