java - 如何从 java 中的文本文件创建字符串数组列表?

标签 java file arraylist text

我正在尝试创建一个程序,允许老师从名册中抓取学生,然后将他们随机分组。我计划从文本文件创建一个数组列表,其中包含一堆学生姓名。我需要帮助从文件中提取学生姓名,然后将他们的姓名插入数组列表中。

这里是数组派上用场的地方(其他地方也有,但程序不完整):

 try {
     System.out.println("Please enter the name of the student that you would like to add to the file as \"Last name, First name\"");
     PrintWriter outputStream = new PrintWriter(new FileOutputStream(fileName, true));  
     Scanner sc = new Scanner(System.in);
     String s = sc.next();
     outputStream.println(s);
     sc.close();
     outputStream.close();
   } catch (FileNotFoundException ex) {
       ex.printStackTrace();
   } catch (IOException ex) {
       ex.printStackTrace();
   }

我还需要在这个程序中涉及几个类,所以我创建了这个类,我的想法是我可以为存档的学生创建一个开放变量。

public class Name {

    private String studentName;

    public Name() {
    }

    public Name(String studentName) {
        this.studentName = studentName; 
    }


    public String getstudentName() {
        return studentName;
    }

    public void setstudentName(String studentName) {
        this.studentName = studentName;
    }

}

这是包含一些名称的文本文件,对我来说具有挑战性的部分是名称之间有一个逗号分隔(也许我应该删除它?):

 Ospina, Bryan
 Patel, Krupa
 Preite, Nicholas   
 Quigley, Kevin
 Rubet, Aaron   
 Said, Abanoub
 Sidler, Allen
 Thiberge, Daniel
 Thota, Raajith
 Tripathi, Rashi    
 Tsang, Johnny
 Velovic, Joseph
 Victor, Samuel
 Whitted-Mckoy, Eric
 Wu, Michelle

编辑:压缩代码

最佳答案

使用 Stream,您将无法将其用于作业...

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;
import java.util.stream.Collectors;

public class Demo {
    public static void main(String[] args) throws IOException {

        final String filename = "whatever";

        List<Name> list =
            Files.lines(Paths.get(filename))   // Strings, lines in the file
            .map(line -> line.split(","))      // String[], split by ,
            .map(split -> split[1] + split[0]) // String, joined again
            .map(Name::new)                    // Name, make a Name object from String
            .collect(Collectors.toList());     // collect into a List<Name
    }

    public static class Name {
        private final String studentName;
        public Name(String studentName) {
            this.studentName = studentName;
        }
        public String getstudentName() {
            return studentName;
        }
    }
}

关于java - 如何从 java 中的文本文件创建字符串数组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47566944/

相关文章:

java - 使用 Java 8 Streams 从列表中仅获取所需的对象

java - BeanNameAware 的用例

java - 如何计算当前方向和GPS点之间的角度

java - 使用 Mockito : Matching multiple arguments in a private static method?

javascript - 使用 Javascript 将文件插入 html 页面?

java - 为什么子列表不适用于 List<Object>?

java - 用 while 循环结束我的游戏 -- java

java - ScheduledExecutorService 与使用 Thread.sleep() 滚动您自己的 Runnable 之间的区别

javascript - 外部还是内联 JavaScript? - 页面加载时间

Python:字典列表 - 使用键作为标题,行是值(天真的方式)