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

时间:2017-11-30 06:11:31

标签: java file arraylist text

我正在尝试创建一个程序,允许教师从名单中抓住学生,然后将他们扔进随机组。我打算从文本文件中创建一个arraylist,上面有一堆学生名字。我需要帮助从文件中提取学生姓名,然后将他们的名字插入数组列表。

这里阵列会派上用场(其他地方也是如此,但程序不完整):

 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

编辑:简化代码

4 个答案:

答案 0 :(得分:1)

使用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;
        }
    }
}

答案 1 :(得分:0)

  

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

你需要阅读直到文件结束,我正在使用BufferedReader显示其中一种方法,直到文件结束。

BufferedReader br = new BufferedReader(new FileReader("pathToYourFile"));
String input = null;
String [] splittedInput = null;
String fullName = null;
List<Name> names = new ArrayList<>(); // Maintaining all the names
while((input = br.readLine()) != null) { // Until the End
 splittedInput = input.split(",");
 fullName = splittedInput[1] + splittedInput[0]; // Since file stoes lastname,firstname
  names.add(new Name(fullName));
}

//Now names list contains all Name Object

答案 2 :(得分:0)

以下是完成任务的替代方法:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Scan {

    public static void main(String[] args) {
        String fileName = "text.txt";
        List<Name> names = new ArrayList<>();

        try (Scanner scan = new Scanner(new File(fileName))) {
            while (scan.hasNext())
                names.add(new Name(scan.nextLine().replace(",", "")));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        System.out.println(names);
    }

    public static class Name {
        private final String studentName;

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

        public String getstudentName() {
            return studentName;
        }

        @Override
        public String toString() {
            return studentName;
        }
    }
}

通过使用课程Scanner,您可以阅读以下文件:Scanner scan = new Scanner(new File(fileName))。逐行读取文件:scan.nextLine()直到文件末尾:while (scan.hasNext())。创建new instance的{​​{1}}:Name并将其添加到new Name(scan.nextLine().replace(",", ""))list。要删除使用names.add(...),replace(",", "")方法的String

答案 3 :(得分:0)

请检查:

Manipulate data from a file and then store it into an array

我有完全相同的。