简体   繁体   English

使用扫描仪从 Java 中的文本文件中获取和存储变量

[英]Get and store variables from a text file in Java using scanner

i've been trying to search how do I separate the variable name and content in the txt file and store each in the variable of the object but I can't seem to find one.我一直在尝试搜索如何将 txt 文件中的变量名称和内容分开并将每个存储在 object 的变量中,但我似乎找不到。 The code below works only if I don't add the variable names so I'm wondering how can I split it so that I can assign the content of the file to the object.下面的代码仅在我不添加变量名时才有效,所以我想知道如何拆分它,以便我可以将文件的内容分配给 object。

subjects.txt主题.txt

id=1 name=biology instructor=John Smith room=2

Java file Java文件

public class Subject {
   Integer id;
   String name;
   String instructor;
   Integer room;

   public void importSubject() throws IOException{
   //gets data from file and places it into variable
      File list = new File("subjects.txt");
      Scanner reader = new Scanner(list);
      while (reader.hasNextLine()) {
        String [] data = reader.newLine.split("=");
        this.id = Integer.parseInt(data[0]);
        this.name = data[1];
        this.instructor = data[2];
        this.room = Integer.parseInt(data[3]);
      }
   } 
}

Assuming the contents of the file always go in the order of "id", "name", "instructor", "room", one way to do this is to use a custom delimiter for the scanner:假设文件的内容总是 go 按“id”、“name”、“instructor”、“room”的顺序,一种方法是为扫描仪使用自定义分隔符:

Scanner reader = new Scanner(list);
reader.useDelimiter("\\s*(id|name|instructor|room)=");

id= , name= , instructor= and room= (including leading spaces) all match the delimiter pattern \s*(id|name|instructor|room)= , so the scanner will only give us the tokens in between those delimiters, which are: id=name=instructor=room= (包括前导空格)都匹配分隔符模式\s*(id|name|instructor|room)= ,因此扫描仪只会给我们这些分隔符之间的标记,这是:

  • 1
  • biology
  • John Smith
  • 2

exactly the things you want.正是你想要的东西。

So you would do:所以你会这样做:

if (reader.hasNextLine()) {
    this.id = reader.nextInt();
    this.name = reader.next();
    this.instructor = reader.next();
    this.room = reader.nextInt();
}

I'm not sure why you are using a loop - you only have one set of fields to initialise.我不确定您为什么要使用循环-您只有一组要初始化的字段。 If there are multiple lines in the file and you want to create a Subject for each line, you'd create a ArrayList<Subject> :如果文件中有多行并且您想为每一行创建一个Subject ,您将创建一个ArrayList<Subject>

public static List<Subject> readSubjects() throws IOException {
    File list = new File("subjects.txt");
    Scanner reader = new Scanner(list);
    ArrayList<Subject> list = new ArrayList<>();
    while (reader.hasNextLine()) {
        Subject newSubject = new Subject();
        newSubject.id = reader.nextInt();
        newSubject.name = reader.next();
        newSubject.instructor = reader.next();
        newSubject.room = reader.nextInt();
        list.add(newSubject);
    }
    return list;
}

The idea is that after you after split by = you get a part.这个想法是,在你被=分割之后,你得到了一部分。 And you have to split that part by " " , the last part is the key of the next = part, and before that is the value of the previous = split part.你必须用" "分割那部分,最后一部分是下一个=部分的键,在这之前是前一个=分割部分的值。

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;

public class Main2 {

    public static void main(String[] args) throws Exception {
        Subject subject = new Subject();
        subject.importSubject();
        System.out.println(subject);
    }
}

class Subject {
    Integer id;
    String name;
    String instructor;
    Integer room;

    public void importSubject() throws IOException {
        //gets data from file and places it into variable
        File list = new File("subjects.txt");
        Scanner reader = new Scanner(list);
        while (reader.hasNextLine()) {
            // biology instructor  --- John Smith room
            String[] stringBetweenEqualsSign = reader.nextLine().split("=");

            String[] afterId = stringBetweenEqualsSign[1].split(" ");
            this.id = Integer.parseInt(String.join(" ", Arrays.copyOf(afterId, afterId.length - 1)));

            String[] afterName = stringBetweenEqualsSign[2].split(" ");
            this.name = String.join(" ", Arrays.copyOf(afterName, afterName.length - 1));

            String[] afterInstructor = stringBetweenEqualsSign[3].split(" ");
            this.instructor = String.join(" ", Arrays.copyOf(afterInstructor, afterInstructor.length - 1));

            this.room = Integer.parseInt(stringBetweenEqualsSign[4]);
        }
    }

    @Override
    public String toString() {
        return "Subject{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", instructor='" + instructor + '\'' +
                ", room=" + room +
                '}';
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM