从textfile(这里是初学者)java加载文本

时间:2017-12-19 08:31:18

标签: java

这是地址簿项目的代码段。我想从文本文件加载文本,但我被卡住,因为我创建的类不能转换为字符串,不知道如何扫描。

那么如何加载两个字符串,例如String firstname和String familyname? (编辑)我已经编辑了所以我添加了缺少的方法和类。

class Person {
  int id;
  String firstname;
  String familyname;

  Person(int id, String firstname, String familyname) {
    this.id = id;
    this.firstname = firstname;
    this.familyname = familyname;
  }

  public void setId(int id) {
    this.id = id;
  }

  public void setFirstname(String firstname) {
    this.firstname = firstname;
  }

  public void setFamilyname(String familyname) {
    this.familyname = familyname;
  }

  public int getId() {
    return this.id;
  }

  public String getFirstname() {
    return this.firstname;
  }

  public String getFamilyname() {
    return this.familyname;
  }
}

class AddressBook {
  ArrayList<Person> addresses = new ArrayList<Person>();

  int id = 0;

  AddressBook() {
    load();

  public void add(String firstName, String familyName) {
    Person person = new Person(++id, firstName, familyName);
    addresses.add(person);
  }

  public void load() {
    try {
      File file = new File("AddressBook.txt");
      Scanner scanner = new Scanner(file);
      Person person;
      while (scanner.hasNextLine()) {
        person = scanner.nextLine();
        add(person.getFirstname(),person.getFamilyname());
      } 
    } catch (IOException e) {
      System.out.println("Error in input/output");
    }
  }

  public void save() {
    try {
      PrintWriter writer = new PrintWriter("AddressBook.txt", "UTF-8");
      for (Person person: addresses) {
        writer.println(person.getFirstname()+" "+person.getFamilyname());
      }
      writer.close();           
    } catch (IOException e) {
      System.out.println("Error in input/output");      
    }
  }
}

1 个答案:

答案 0 :(得分:0)

试试这个代码段。从文件中获取行,使用空格拆分并使用。

public void load() {
        try {
            File file = new File("AddressBook.txt");
            Scanner scanner = new Scanner(file);
            Person person;
            while (scanner.hasNextLine()) {
                String[] split = scanner.nextLine().split(" ");
                add(split[0], split[1]);
            }
        } catch (IOException e) {
            System.out.println("Error in input/output");
        }
    }