提示信息

java 读取txt

韦佳涵 已关注

在Java中读取txt文件有多种方式,常用的方法包括使用BufferedReaderFileReaderFiles类。下面是几种常见的方法来读取txt文件的示例代码。

方法一:使用 BufferedReaderFileReader

  1. import java.io.BufferedReader;
  2. import java.io.FileReader;
  3. import java.io.IOException;
  4. public class ReadFileExample {
  5. public static void main(String[] args) {
  6. String filePath = "path/to/your/file.txt";
  7. try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
  8. String line;
  9. while ((line = br.readLine()) != null) {
  10. System.out.println(line);
  11. }
  12. } catch (IOException e) {
  13. e.printStackTrace();
  14. }
  15. }
  16. }

方法二:使用 Files 类(Java 7 及以上)

  1. import java.nio.file.Files;
  2. import java.nio.file.Paths;
  3. import java.util.List;
  4. import java.io.IOException;
  5. public class ReadFileExample {
  6. public static void main(String[] args) {
  7. String filePath = "path/to/your/file.txt";
  8. try {
  9. List<String> lines = Files.readAllLines(Paths.get(filePath));
  10. for (String line : lines) {
  11. System.out.println(line);
  12. }
  13. } catch (IOException e) {
  14. e.printStackTrace();
  15. }
  16. }
  17. }

方法三:使用 Scanner

  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.util.Scanner;
  4. public class ReadFileExample {
  5. public static void main(String[] args) {
  6. String filePath = "path/to/your/file.txt";
  7. try (Scanner scanner = new Scanner(new File(filePath))) {
  8. while (scanner.hasNextLine()) {
  9. String line = scanner.nextLine();
  10. System.out.println(line);
  11. }
  12. } catch (FileNotFoundException e) {
  13. e.printStackTrace();
  14. }
  15. }
  16. }

在上述示例中,path/to/your/file.txt应替换为你实际的txt文件路径。

注意事项

  1. 文件路径:确保路径正确且文件存在。
  2. 异常处理:文件读取过程中可能会出现IO异常,需要进行适当的处理。
  3. 编码:如果文件有特定的编码,如UTF-8,可能需要指定编码格式进行读取。
  4. 资源管理:要确保文件资源在读取完毕后正确关闭,推荐使用try-with-resources语句处理可关闭的资源。

选择适合你需求的方法来读取文件内容。如果你需要处理大文件,使用BufferedReader可能会更有效率,因为它是基于缓冲的读取。

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
韦佳涵 关注 已关注

最近一次登录:2024-09-18 20:38:42   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图