简体   繁体   中英

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. 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.

subjects.txt

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

Java file

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:

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:

  • 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> :

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 +
                '}';
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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