有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何读取txt文件并向数组数据输入信息?

我有一个关于自动将数据从txt文件输入数组的问题。我有这个文件txt下面,我想采取像医生和宠物输入2阵列。 医生:姓名和专业 private ArrayList arrDoctor=新ArrayList<&燃气轮机;(); 宠物:姓名、类型、大小、体重、年龄、医生。 private ArrayList arrPet=新的ArrayList<&燃气轮机;();

这是我的档案。txt

doctors
name joao
specialisation cat
name maria
specialisation dog
pets
name lara
type cat
size small
weight 4.0
age 5
doctor joao
name biro
type dog
size large
weight 15.0
age 12
doctor maria
name benny
type cat
size large
weight 7.0
age 10
doctor none

共 (1) 个答案

  1. # 1 楼答案

    您需要读取文件,例如:

    try {
          File file = new File("PATH/TO/FILE/filename.txt");
          Scanner myReader = new Scanner(file);
          while (myReader.hasNextLine()) {
            String line = myReader.nextLine(); // this will be your single line in a file
            someLogicHere(line);
          }
          myReader.close();
        } catch (FileNotFoundException e) {
          // handle file not found
        }
    

    将一行代码解析成程序后,您需要一些逻辑来确定这是医生还是宠物,并在代码中创建对象

    这个逻辑看起来像这样:

    String firstLine = "name joao";
    String secondLine = "specialisation cat";
    String name = firstLine.replace("name ", ""); // get rid of this name prefix
    String specialisation = secondLine.replace("specialisation ", ""); // get rid of this specialisation prefix
    Doctor doctor = new Doctor(name, specialisation);
    

    我强烈建议将医生和宠物分成不同的文件,这样对你来说更容易。另外,让医生和宠物每一行写一行,而不必解析一行或多行来创建单个对象,这会更容易。 例如name joao specialisation cat