【问题标题】:Reading a text file & adding the content to an ArrayList读取文本文件并将内容添加到 ArrayList
【发布时间】:2019-04-12 13:22:36
【问题描述】:

我正在学习从文本文件中获取输入并通读内容的所有不同方法。我正在努力使用 try - catch 块(带有资源),并读取文件名。

以下是到目前为止我为这部分写的内容:-

public static void main(String[] args) 
{

    ArrayList<StationRecord> data = new ArrayList<>();
    String stationName = null;

    Scanner scan = new Scanner(System.in);
    System.out.println("What is the filename?");
    String input = scan.nextLine();
    File file = new File(input);

    try(BufferedReader in = new BufferedReader(new FileReader(file))){

      while(scan.hasNext()){

       stationName = scan.nextLine();
       int yearMonthDay = scan.nextInt();
       int max = scan.nextInt();
       int min = scan.nextInt();
       int avg = scan.nextInt();
       double dif = scan.nextDouble();

       StationRecord sr = new StationRecord(yearMonthDay, max, min, avg, dif);
       data.add(sr);
      }

    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    catch(Exception e)
    {
        e.printStackTrace();

    }
}

我不仅要为一个文件,还要为其中的两个文件这样做。无论如何,这是一个输入示例:-

控制台:文件名是什么?

TempData2018a.txt

输入后,我试图遍历文本文件中的数据并将其添加到 StationRecord 类型的 ArrayList(我的其他类)。

任何建议和指导将不胜感激!此外,关于如何使用 2 个文件执行此操作的任何输入都会很棒!

编辑:.txt 文件数据示例

PITTSBURGH ALLEGHENY CO AIRPORT PA
20180101 11 2 7 -22.614762
20180102 12 5 9 -20.514762
20180103 23 2 13 -16.414762

我试图将整个第一行存储在一个名为 stationName 的变量中。然后我尝试将下一个 int、int、int、int double 存储在 StationRecord 类型的 ArrayList 中。

【问题讨论】:

  • 好吧,你根本没有使用缓冲阅读器。您只是从扫描中读取,而扫描是从 System.in 读取的扫描仪。如果要使用 SCanner 从文件中读取,则需要构造 Scanner,而不是 BufferedReader。 docs.oracle.com/javase/8/docs/api/java/util/…
  • @Swifty120 您的代码完全不正确。为什么要使用 Scanner 类来读取 StationRecord 类的状态?您不是从 .txt 文件中读取这些值吗?你不应该使用 BufferedReader 类吗?您能否在问题中也发布 TempData2018a.txt 的内容?
  • 两个文件是什么意思。您想将数据应用于 arraylist 转换为两个文件吗?
  • @Abhinav 抱歉,我还没有学到任何东西。.txt 文件的内容现在正在编辑中。
  • 通过两个文件,我的意思是我有一个 TempData2018a.txt 和一个 TempData2018b.txt 可以读入。

标签: java java-8 java-io


【解决方案1】:

使用 Java 7Java 8 API 的 功能,您可以解决如下问题:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class LineOperation {

private static List<String> lines;

public static void main(String[] args) throws IOException {

    lines = Collections.emptyList();

    try {
          lines = Files.readAllLines(Paths.get("C:\\Users\\Abhinav\\Downloads\\TempData2018a.txt"), StandardCharsets.UTF_8);

          String stationName = lines.get(0);

          String[] arr = null;

          ArrayList<StationRecord> data = new ArrayList<>();

          for(int i=1;i<lines.size();i++) {

              arr = lines.get(i).split(" ");

              data.add(new StationRecord(Long.parseLong(arr[0]), Integer.parseInt(arr[1]), Integer.parseInt(arr[2]), Integer.parseInt(arr[3]), Double.parseDouble(arr[4])));
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
}
}

但我强烈建议您参考以下链接以进一步了解 Java I/O:-

  1. Java – Read from File

  2. Read a File into an ArrayList

【讨论】:

  • 谢谢,这让我上路了。只需要将它实现到我的测试程序中。链接也不错,我去看看!
【解决方案2】:

由于这是 2018 年,请停止使用 new File(..) 并开始使用 nio API。当您使用 Java 8 时,您可以在这里轻松实现您想要实现的目标!所以,你可以像这样创建你的StationRecord

Path filePath = Paths.get(pathToFile);

       String stationName =  Files.lines(filePath)
            .findFirst()
            .get();

        List<StationRecord> stationRecords =
            Files.lines(filePath)
                .skip(1) //Skip first line since it has station name
                .map(line -> line.split("\\s")) // split at a space starting from 2nd line
                .map(
                stationData -> new StationRecord(Integer.valueOf(stationData[0]),
                    Integer.valueOf(stationData[1]), Integer.valueOf(stationData[2]),
                    Integer.valueOf(stationData[3]), Double.valueOf(stationData[4]))) // Create StationRecord object using the split fields
                .collect(Collectors.toList()); // Collect result to an ArrayList

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多