繁体   English   中英

如何从txt文件读取行并将每行添加到LinkedList类型?

[英]How do I read lines from a txt file and add each line to a type LinkedList?

因此,基本上,该程序调用以使用类类型LinkedList来存储文本文件中的行。 当然,我是一个单独的课程,所以这就是我正在使用的LinkedList的类型。 这是程序正在读取的txt文件

CPSC141 Computer_Organization   3   D
CPSC130 Computer_ProgrammingI   3   B
Math140 Calculus_I  4   E
CPSC232 Assembler_Languages 3   B
CPSC131 Computer_ProgramingII 3 A
Math141 Calculus_II 4   B

这是我的代码

File inFile = new File("courses.txt");
    Scanner f = new Scanner(inFile);
    while (f.hasNextLine())
    {
        Courses.add(f);
    }
    f.close();

问题是我收到一条错误消息,内容如下:

method.java.util.Collection.add(Course) is not applicable;
(argument mismatch; java.util.Scanner cannot be converted to Course);

我不知道如何将字符串从txt文件转换为类型Course(我的单独班级)

在Java 8中,您可以简单地使用:

List<String> yourList = Files.readAllLines(Paths.get("courses.txt"));

fScanner实例。 将其更改为在下一行中读取的行。

//from
Courses.add(f);
//To
Courses.add(f.nextLine());

现在,变量f是Scanner实例。 您可以使用String.valueOf或toString()方法将其转换为字符串,也可以将整个行读取为字符串。

暂无
暂无

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

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