【问题标题】:How can I store values from a text file into an array in java如何将文本文件中的值存储到java中的数组中
【发布时间】:2020-07-31 14:20:37
【问题描述】:

我正在使用 Java 读取文本文件,我需要将此文本文件的内容存储在数组中,并将其作为引用传递,例如新类。

这是我的txt文件的结构:

牛津

软件工程师、管理、法律

普林斯顿

数学、经济、社会学

这是具有文件结构的类:

public class University {
private String name;
private String[] careers;

public University() {
}

public University(String name, String[] careers) {
    this.name = name;
    this.careers = careers;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String[] getCareers() {
    return careers;
}

public void setCareers(String[] careers) {
    this.careers = careers;
}

这是学生类,具有大学类的大学和职业作为属性:

public class Student {
private String name;
private University university;
private String career;

public Student() {
}

public Student(String name, University university, String career) {
    this.name = name;
    this.university = university;
    this.career = career
}

public String getName(){
    return name;
}

public string setName(String name){
    this.name = name;
}

public University getUniversity(){
    return university;
}

public University setUniversity(University university){
    this.university = university;
}

}

如您所见,我的职业属性是一个数组。我想将文本文件中的职业和大学存储在我的学生职业数组中。并做这样的事情:

示例输入:

System.out.println("Greetings student, to what career you wanna set up to");
//here I wanna type the name of the career from the careers list from the text file

然后有这样的东西:

预期输出示例:

System.out.println("Congrats new student, your new career is" + career);

这是我读取文本文件并打印它的主要方法:

public static void readFiles() throws FileNotFoundException, IOException {
    BufferedReader readBuffer = new BufferedReader(new FileReader("C:\\Users\\Roberto\\Documents\\NetBeansProjects\\sistemaBecas\\src\\ficheros\\Universidad.txt"));
    String docLine;
    ArrayList<String> registerList = new ArrayList<String>();
    while ((docLine = readBuffer.readLine()) != null) {
        registerList.add(docLine);
    }
    String[] arrayDocument = registerList.toArray(new String[0]);        
    for (int i = 0; i < arrayDocument.length; i++) {
        System.out.println(Array.get(arrayDocument,i));
        
    }
}

我该怎么做?

【问题讨论】:

  • 目前还不清楚你的问题是什么。请清楚地发布您的问题/要求并附上完整的代码。顺便说一句,不要使用Array.get(arrayDocument,i),只使用arrayDocument[i]
  • 您能准确地显示实际的文件格式吗?您可以将文本括在&lt;pre&gt;&lt;/pre&gt; 标记中。或者有些人更喜欢代码块。

标签: java arrays indexing


【解决方案1】:

试试这个。

String file = "C:\\Users\\Roberto\\Documents\\NetBeansProjects\\sistemaBecas\\src\\ficheros\\Universidad.txt";
List<String> lines = Files.readAllLines(Paths.get(file));
List<University> universities = new ArrayList<>();
for (int i = 0; i < lines.size(); i += 2)
    universities.add(new University(lines.get(i), lines.get(i + 1).split("\\s*,\\s*")));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 2019-07-26
    相关资源
    最近更新 更多