java 读取文本内容

2023-07-13  本文已影响0人  饱饱想要的灵感

IO流实现

在Java中,可以使用FileReaderBufferedReader类来读取文本文件的内容。

首先,需要创建一个FileReader对象来指定要读取的文件路径,然后再创建一个BufferedReader对象来读取文件内容。可以使用BufferedReader对象的readLine()方法来逐行读取文件内容。

下面是一个示例代码:

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

public class ReadTextFile {
    public static void main(String[] args) {
        try {
            // 创建FileReader对象来读取文件
            FileReader fileReader = new FileReader("file.txt");
            // 创建BufferedReader对象来读取文件内容
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            String line;
            // 逐行读取文件内容并打印
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }

            // 关闭流
            bufferedReader.close();
            fileReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上述代码中,file.txt是要读取的文件名,可以根据实际情况进行替换。使用BufferedReaderreadLine()方法读取文件内容时,会返回每行的内容,当读取到文件末尾时,返回null

NIO类库实现

使用NIO类库可以实现更高效的文件读取,下面是一个使用NIO类库读取文本内容的示例代码:

import java.io.IOException;
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 NIOExample {

    public static void main(String[] args) {
        Path filePath = Paths.get("path/to/file.txt");

        try {
            List<String> lines = Files.readAllLines(filePath, StandardCharsets.UTF_8);
            for (String line : lines) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上面的代码中,我们首先创建了一个Path对象来表示要读取的文件路径。然后,我们使用Files.readAllLines()方法读取文件的所有行,并指定了文件的编码格式为UTF-8。最后,我们通过遍历得到的行列表来逐行打印文件内容。

需要注意的是,在使用NIO类库进行文件读取时,文件路径的表示方法是不同的。相比于传统的File类,NIO使用了PathPaths类来表示文件路径。通过Paths.get()方法可以根据给定的字符串创建一个Path对象,然后就可以使用Files类提供的各种方法来进行文件操作了。

或者使用了NIO的FileChannel和ByteBuffer来读取文件内容:

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;

public class FileReader {

    public static void main(String[] args) {
        Path path = Paths.get("path/to/file.txt");

        try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ)) {
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            while (channel.read(buffer) != -1) {
                buffer.flip();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);
                System.out.print(new String(bytes, StandardCharsets.UTF_8));
                buffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在这个示例中,首先通过调用Paths.get()方法获取要读取的文件的路径。然后使用FileChannel.open()方法打开文件通道,并使用StandardOpenOption.READ选项指定以只读模式打开文件。

接下来,创建一个ByteBuffer实例,使用allocate()方法分配一定大小的内存空间。然后使用while循环,不断调用channel.read()方法读取通道中的数据,直到读取到文件末尾。

在每次读取数据后,调用buffer.flip()方法将缓冲区从写模式切换到读模式。然后使用buffer.remaining()方法获取缓冲区中的有效数据大小,创建一个对应大小的字节数组,然后使用buffer.get()方法将数据从缓冲区中取出,并使用new String()方法将字节数组转换为字符串。

最后,调用buffer.clear()方法清空缓冲区,并继续下一次读取操作。

注意,在使用完文件通道后,需要在finally或使用try-with-resources语句块中关闭文件通道,以释放资源。

请将"path/to/file.txt"替换为实际的文件路径,然后运行上述代码即可读取文件内容。

上一篇 下一篇

猜你喜欢

热点阅读