如何在 Java 中读取文件

x33g5p2x  于2021-10-16 转载在 Java  
字(4.1k)|赞(0)|评价(0)|浏览(455)

在本文中,您将学习如何使用 Java 提供的各种类和实用方法(如 BufferedReaderLineNumberReader、​​[[$2$])来读取 Java 中的文本文件或二进制(图像)文件]]、Files.linesBufferedInputStreamFiles.readAllBytes 等。

让我们借助示例来看看在 Java 中读取文件的各种不同方式。

Java 使用 BufferedReader 读取文件

BufferedReader 是一种在 Java 中读取文本文件的简单而高效的方法。它从字符输入流中读取文本。它缓冲字符以提供有效的读取。

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class BufferedReaderExample {
    public static void main(String[] args) {
        Path filePath = Paths.get("demo.txt");
        Charset charset = StandardCharsets.UTF_8;

        try (BufferedReader bufferedReader = Files.newBufferedReader(filePath, charset)) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException ex) {
            System.out.format("I/O error: %s%n", ex);
        }
    }
}

Java 使用 Files.readAllLines() 逐行读取文件

Files.readAllLines() 是 Java NIO 的 Files 类的一个实用方法,它读取文件的所有行并返回包含每一行的 List<String>。它内部使用 BufferedReader 来读取文件。

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class FilesReadAllLinesExample {
    public static void main(String[] args) {
        Path filePath = Paths.get("demo.txt");
        Charset charset = StandardCharsets.UTF_8;
        try {
            List<String> lines = Files.readAllLines(filePath, charset);
            for(String line: lines) {
                System.out.println(line);
            }
        } catch (IOException ex) {
            System.out.format("I/O error: %s%n", ex);
        }
    }
}

Java 使用 Files.lines() 逐行读取文件

Files.lines() 方法从文件中读取所有行作为 Stream。您可以使用 forEachmap 等 Stream API 方法来处理文件的每一行。

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FilesLinesExample {
    public static void main(String[] args) {
        Path filePath = Paths.get("demo.txt");
        Charset charset = StandardCharsets.UTF_8;

        try {

            Files.lines(filePath, charset)
                    .forEach(System.out::println);

        } catch (IOException ex) {
            System.out.format("I/O error: %s%n", ex);
        }
    }
}

Java 使用 LineNumberReader 逐行读取文件

LineNumberReader 是一个缓冲的字符流读取器,用于跟踪行号。您可以使用此类逐行读取文本文件。

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class LineNumberReaderExample {
    public static void main(String[] args) {
        Path filePath = Paths.get("demo.txt");
        Charset charset = StandardCharsets.UTF_8;

        try(BufferedReader bufferedReader = Files.newBufferedReader(filePath, charset);
            LineNumberReader lineNumberReader = new LineNumberReader(bufferedReader)) {

            String line;
            while ((line = lineNumberReader.readLine()) != null) {
                System.out.format("Line %d: %s%n", lineNumberReader.getLineNumber(), line);
            }
        } catch (IOException ex) {
            System.out.format("I/O error: %s%n", ex);
        }
    }
}

Java 使用 BufferedInputStream 读取二进制文件(图像文件)

到目前为止,本文中提供的所有示例都是从字符输入流中读取文本数据。如果您正在读取二进制数据(例如图像文件),则需要使用字节输入流。

BufferedInputStream 允许您读取原始字节流。它还缓冲输入以提高性能。

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

public class BufferedInputStreamImageCopyExample {
    public static void main(String[] args) {
        try(InputStream inputStream = Files.newInputStream(Paths.get("sample.jpg"));
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);

            OutputStream outputStream = Files.newOutputStream(Paths.get("sample-copy.jpg"));
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream)) {

            byte[] buffer = new byte[4096];
            int numBytes;
            while ((numBytes = bufferedInputStream.read(buffer)) != -1) {
                bufferedOutputStream.write(buffer, 0, numBytes);
            }
        } catch (IOException ex) {
            System.out.format("I/O error: %s%n", ex);
        }
    }
}

Java 使用 Files.readAllBytes() 将文件读入 []byte

如果要读取字节数组中文件的全部内容,则可以使用 Files.readAllBytes() 方法。

import com.sun.org.apache.xpath.internal.operations.String;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FilesReadAllBytesExample {
    public static void main(String[] args) {
        try {
            byte[] data = Files.readAllBytes(Paths.get("demo.txt"));

            // Use byte data
        } catch (IOException ex) {
            System.out.format("I/O error: %s%n", ex);
        }

    }
}

相关文章