java - 将指定格式的文件读入ArrayList

标签 java arraylist filereader

我有这种特定格式的文件:

0  
2 4   
0 1 A  
0 5 B  
1 1 A  
1 3 B  
2 6 A  
2 4 B  
3 6 A  
3 4 B  
4 6 A  
4 4 B  
5 1 A  
5 5 B  
6 6 A  
6 2 B  
  • 第 1 行 = 开始状态
  • 第 2 行 = 接受状态
  • 第 3 行 - n = 转换表
  • 第一行 = 状态
  • 第二行 = 说明
  • A,B = 符号

Java 中的 FileReader 如何将这些文件读入 5 个不同的 ArrayList(开始状态、最终状态、状态输入、状态输出和符号)?

最佳答案

最好使用Scanner这里:

static class State {
    int in;
    int out;
    String symbol;

    State(int in, int out, String symbol) {
        this.in = in;
        this.out = out;
        this.symbol = symbol;
    }

    @Override
    public String toString() {
        return in + " " + out + " " + symbol;
    }
}

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

    Scanner s = new Scanner(new File("input.txt"));

    int startState = Integer.parseInt(s.nextLine());
    List<Integer> acceptStates = new LinkedList<Integer>();
    List<State> states = new LinkedList<State>();

    Scanner st = new Scanner(s.nextLine());
    while (st.hasNextInt())
        acceptStates.add(st.nextInt());

    while (s.hasNextInt())
        states.add(new State(s.nextInt(), s.nextInt(), s.next()));

    System.out.println(startState);
    System.out.println(acceptStates);
    System.out.println(states);

    // logic...
}

关于java - 将指定格式的文件读入ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4237850/

相关文章:

java - 在 ReSTLet/GAE 中发送回压缩的 JSON

java - 如何在android中获取字符串数组

java - 将两个或多个数组列表合并到一个数组列表中

java - 将数据添加到 ArrayList 并删除旧的

Jenkins 参数化构建不创建文件

javascript - 如何读取 XMLHttpRequest.onreadystatechange 回调函数中 FileReader.onloadend 中定义的变量值?

java - 如何让一个 JNI 应用程序在 Linux 上支持多个版本的 JVM?

javascript - 在 Java 中调用 Javascript 事件

javascript - 如何删除嵌套数组中的特殊字符?

java - java中的文件读取