java - Java从文件中读取数据到数组中

标签 java arrays arraylist

在我的程序中,我要求用户输入主题名称和主题代码,我将其传递到 subject.txt 文件,例如:

TestSubject 类内部 -

//ask the user to input a subject name
System.out.println("Please enter a Subject Name");
//assign each input to a side
String subjectName = input.nextLine();

//ask the user to input a subject code
System.out.println("Please enter a Subject Code");
String subjectCode = input.nextLine();

//add records to the file
subject.addRecords(subjectName, subjectCode);

在学科类别内 -

//add the records of valid subject name and subject code    
public void addRecords(String name, String code) {
    try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("subjects.txt", true)))) {
        out.printf(name);
        out.printf("\n");
        out.printf(code);
        out.printf("\n");
        out.close();
    }catch (IOException e) {

    }
}

然后我想读取该文件并将数据传递到数组列表。该文件可能类似于:

Testing 1
ABC123
Testing 2
DEF456
Testing3
GHI789

我想将它传递给一个数组列表,这样我就可以针对这个数组处理其他方法,例如排序,看看是否有相同的等等。

//read data from subjects file and place in an array
public void readData(){
    Scanner input = new Scanner("subjects.txt");
    while (input.hasNext()) {
        String subjectName = input.nextLine();
        String subjectCode = input.nextLine();
    }

    ArrayList<String> subjectNames = new ArrayList<String>();
    ArrayList<String> subjectCodes = new ArrayList<String>();

    //add the input to the arrays

    subjectNames.add(subjectName);
    subjectNames.add(subjectCode);

    //display the contents of the array

    System.out.println(subjectNames.toString());
    System.out.println(subjectCodes.toString());
}

即使有一个很好的教程,我也许能够指出正确的方向......

最佳答案

感谢您编辑您的帖子。当我能看到问题的根源时,提供帮助就容易多了。

您每两行检查一次 hasNext() 。应该检查每一行,因为您不应该相信文本文件是您所期望的,并且应该在它不是时显示一条信息丰富的错误消息。

您还在循环范围内声明了字符串,因此循环之外的任何内容都不会知道它们是什么。将 subjectCode 插入 subjectNames 集合可能不是您想要的。事实上,每个 nextline() 都会步进到最后一个字符串值。这意味着您忘记了在循环的先前迭代中完成的所有工作。

collections.add() 调用,而不是字符串,应该在循环中。确保在循环之前声明集合并将其添加调用放入循环中。看看您是否获得有用的结果。

读一下“Reading a plain text file in Java ”。

关于java - Java从文件中读取数据到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23717554/

相关文章:

c - 如何在 C 中向 double 组添加值

java - 从 java ArrayList 转换为 scala Array 时,特征列表中的 toArray 方法缺少参数

java - 如何将新对象添加到已创建的列表中?

Javafx - 文本流 + 文本 = 非常慢

java - 给定多边形的坐标求长度

java - 如何构建变更跟踪系统——而非审计系统

php - 通过 $_SESSION 从一个脚本发送到另一个脚本时数据丢失

java - 非顺序索引集合

java - 在 Spring 中使用 Java 驱动程序的无尽 MongoDB ReplicaSetStatus 更新程序异常

java - 为什么通过 ant 的 javadoc 不显示我方法的一些文档?