【问题标题】:Read formatted text file into array list JAVA将格式化的文本文件读入数组列表 JAVA
【发布时间】:2014-09-30 09:18:21
【问题描述】:

我需要我的 java 程序来读取一个格式化的文本文件,我将举例说明它是如何格式化的

http://i.stack.imgur.com/qB383.png

所以#1 是列出的国家数量,A 是区域,新西兰是国家。

所以我知道我需要读取 # 之后的数字,这是运行循环的次数,然后下一行包含区域名称,这将是数组列表的名称。但至于实际实现这一点,我非常迷茫。

目前我的代码是这样的,

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;


public class destination{

    String zone;
    ArrayList<String> countries;

    public Object destinationList(){

        Scanner s = null;
        try {
            s = new Scanner(new File("Files/Destination.txt"));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ArrayList<String> destinations = new ArrayList<String>();
        while (s.hasNext()) {
            destinations.add(s.nextLine());

        }
        s.close();

        int sz = destinations.size();

        for (int i = 0; i < sz; i++) {
            System.out.println(destinations.get(i).toString());
        }

        return destinations;
    }

}

但这只是将文本文件转储到数组列表中

【问题讨论】:

  • 在问题中至少发布几行文本文件并添加预期结果。

标签: java arrays arraylist stream


【解决方案1】:

您不需要额外的区域和国家课程,它可以完美地与地图配合使用:

private Map<String, List<String>> destinations = new HashMap<>();

要使用文件中的值填充地图,您可以编写类似(未测试)的内容。

Scanner s = new Scanner(new File("Files/Destination.txt"));
int currentCount = 0;
String currentZone = "";
while(s.hasNextLine()) {
    String line = s.nextLine();
    if (line.startsWith("#") { // number of countries
        currentCount = Integer.parseInt(line.substring(1));
    } else if (line.length() == 1) { // zone
        currentZone = line;
        destinations.put(currentZone, new ArrayList<String>(currentCount);
    } else { // add country to current zone
        destinations.get(currentZone).add(line);
    }
}

【讨论】:

    猜你喜欢
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2012-11-03
    • 2022-09-26
    • 2018-12-03
    • 1970-01-01
    相关资源
    最近更新 更多