简体   繁体   English

Java-从.txt文件读取到对象

[英]Java - Read from .txt file into a Object

I have an Object Called Question. 我有一个称为问题的对象。 It has the following attributes: 它具有以下属性:

  • String question, option1, option2, option3, answer 字符串问题,选项1,选项2,选项3,答案

  • double difficulty 双重困难

  • int category 整数类别

I have a file called questions.txt which has the information regarding these attributes, attributes are separated by a comma. 我有一个名为questions.txt的文件,其中包含有关这些属性的信息,这些属性用逗号分隔。 (1 Object per line) (每行1个对象)

eg 例如

Carmine is a vivid shade of which colour?,Blue,Green,Yellow,Red,1,2 胭脂红是哪种颜色的鲜艳阴影?,蓝色,绿色,黄色,红色,1,2

I want to read each line of the file creating an Object Question and adding it to an ArrayList called questionBank. 我想阅读文件的每一行,创建一个对象问题并将其添加到一个名为questionBank的ArrayList中。

With the example mentioned above, this would be the result of the new Object created. 对于上述示例,这将是创建新对象的结果。

question = Carmine is a vivid shade of which colour? 问题=胭脂红是哪种颜色的鲜艳阴影?

option1 = Blue 选项1 =蓝色

option2 = Green option2 =绿色

option3 = Yellow option3 =黄色

answer = Red 答案=红色

difficulty = 1 难度= 1

category = 2 类别= 2

I have got the following code so far, but have no idea of how to extract each attribute between the commas so I can use it as an argument during Object instantiation. 到目前为止,我已经获得了以下代码,但是不知道如何在逗号之间提取每个属性,因此我可以在对象实例化期间将其用作参数。

Scanner input = new Scanner(new File("/Users/usaamahpatel/IdeaProjects/sdd_assignment/src/questions.txt"));
    input.useDelimiter(",");

    while (input.hasNext()) {
        System.out.println(input.next());
    }

This is the output I get from the above code: 这是我从上面的代码中获得的输出:

Carmine is a vivid shade of which colour?
Blue
Green
Yellow
Red
1
2

As you can see It prints each item between the commas, how do I extract all attributes per line for one Object and so on? 如您所见,它会打印逗号之间的每个项目,如何为一个对象提取每行的所有属性,依此类推?

I assume you have more than one line in the file, so more than one question, right ? 我假设文件中有多行,所以有多个问题,对吗?

So then use as delimiter not , , but newline to read line by line (or use Files#readLines for that. Then you know each line represent one object. To retrieve the different attributes of the object you can split the line with , and fill the object 因此,请使用不是分隔符,而不是,而是使用newline逐行读取(或使用Files#readLines作为分隔符。然后,您知道每一行都代表一个对象。要检索对象的不同属性,可以使用,物体

Assuming each Question you want is separated by a newline you could use input.nextLine().split(",") to get an array of Strings where each element is an attribute. 假设您要的每个问题都由换行符分隔,则可以使用input.nextLine().split(",")获得一个字符串数组,其中每个元素都是一个属性。 You can then use Double.valueOf() and Integer.valueOf() to parse the difficulty and category to the proper types. 然后,您可以使用Double.valueOf()Integer.valueOf()将难度和类别解析为适当的类型。

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

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