简体   繁体   English

如何将数据从文本文件读取到ArrayList

[英]How do I read data from text file to ArrayList

Assume that entered file have the following data: 假设输入的文件具有以下数据:

101 
alice
102
bob
103
smith

All this data into textfile, as it's shown in program, just enter text file name and read all data and display. 如程序中所示,所有这些数据都将存储到文本文件中,只需输入文本文件名并读取所有数据并显示即可。

I wanna read those two data (number and name ) into ArrayList and display all the data as what I've shown in the program: 我想将这两个数据(number和name)读入ArrayList并将所有数据显示为程序中显示的内容:

class Student {
    private int num;
    private String name;

    public Student(int num, String name) {
        this.num = num;
        this.name= name;
    }

    public String toString() {
        return "[ student number :: "+num+" ] \t [ student name :: 
               "+name+ "]";
    }
}


import java.io.*;
import java.util.*;

class Tester {
    public static void main(String [] aa)throws IOException {
        Scanner kb=new Scanner(System.in);
        System.out.print(" enter file name >> ");
        String filename=kb.nextLine();

        File f = new File(filename);
        kb=new Scanner(f);

        ArrayList<Student> stu =new ArrayList<Student>();

        while(kb.hasNextLine()) {
            int num=kb.nextInt();kb.nextLine();
            String name =kb.nextLine();

            stu.add(num);
            stu.add(name);
        }

        for(int i=0;i<stu.size(); i++) {
            System.out.println(stu.get(i));
        }
    }
}

Since you already made an arraylist of student you can do this inside your text reader(while loop): stu.add(new Student(num, name)); 由于您已经为学生创建了一个数组列表,因此您可以在文本阅读器中进行此操作(while循环):stu.add(new Student(num,name)); what it does is you are creating an object of student and placing it inside the arraylist for every record in your text file. 它的作用是创建一个学生对象,并将其放置在文本文件中每条记录的arraylist内。

Your program should return an error because are attempting to put a String and int into an ArrayList of Students. 您的程序应返回错误,因为试图将Stringint放入ArrayList中。 Also, you only iterates through your ArrayList of students and do not print them out. 同样,您仅遍历学生的ArrayList ,而不打印出来。 Your code should look like this. 您的代码应如下所示。

class Tester {
    public static void main(String[] aa) throws IOException {
        Scanner kb = new Scanner(System.in);
        System.out.print(" enter file name >> ");
        String filename = kb.nextLine();

        File f = new File(filename);
        kb = new Scanner(f);

        ArrayList<Student> stu = new ArrayList<Student>();

        while (kb.hasNextLine()) {
            int num = kb.nextInt();
            kb.nextLine();
            String name = kb.nextLine();

            stu.add(new Student(num, name));
        }

        for (Student s : stu) {
            System.out.println(s.toString());
        }

    }
}

Suppose your file looks like this 假设您的文件如下所示
101 alice 101爱丽丝
102 bob 102鲍勃
103 smith 103史密斯

String fileName = //get by scanner;

//read file into stream, try-with-resources
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
    List<Student> users = new ArrayList<>();
    stream.stream().forEach(user -> {
        List<String> userAttrs = Arrays.asList(user.split("\\s* \\s*"));
        Student userObj = new Student(Integer.parseInt(userAttrs.get(0)), userAttrs.get(1));
        users.add(userObj);
    });

    users.stream().forEach(System.out::println);

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

After I enter first answer problem was edited and now your file looks like 输入第一个答案后,问题已编辑,现在您的文件看起来像
101 101
alice 爱丽丝
102 102
bob 鲍勃
103 103
smith 史密斯

String fileName = //get by scanner;

//read file into stream, try-with-resources
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
    List<String> detailList = stream.collect(Collectors.toList());
    List<Student> students = new ArrayList<>();
    BiFunction<String, String, Student> userFunction = (id, name) -> 
                                 new Student(Integer.parseInt(id), name);

        for (int i = 0; i < detailList.size(); i += 2) {
            students.add(userFunction.apply(
                       detailList.get(i), detailList.get(i+1)));
        }
        students.stream().forEach(System.out::println);

} catch (IOException e) {
    e.printStackTrace();
}
public class Tester {

public static void main(String[] args) {        

    String path = "E:\\b.txt";

    Tester tester = new Tester();

    String[] str = tester.sortData(tester.readFile(path));

    List<Student> list = new ArrayList<Student>();

    for(int i = 0;i < str.length;i = i + 2){
        Student student = new Student();
        student.setNum(Integer.parseInt(str[i]));
        student.setName(str[i + 1]);

        list.add(student);
    }

    for(int i = 0;i < list.size();i++){
        System.out.println(list.get(i).getNum() + " " + list.get(i).getName());
    }

}

public StringBuilder readFile(String path){
    File file = new File(path);
    StringBuilder stringBuilder = new StringBuilder();

    try{
        InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file));
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String lineTxt = null;

        while((lineTxt = bufferedReader.readLine()) != null){
            stringBuilder.append(lineTxt);
        }

    }catch(Exception e){
        System.out.println("erro");
    }

    return stringBuilder;
}

public String[] sortData(StringBuilder words){
    int i = 0;
    int count = 0;
    String str = "\\d+.\\d+|\\w+";
    Pattern pattern = Pattern.compile(str); 
    Matcher ma = pattern.matcher(words);

    String[] data = new String[6];

    while(ma.find()){
        data[i] = ma.group();
        i++;
    }

    return data;
}

} }

class Student{ 班级学生{

private int num;
private String name;

public Student(){

}

public Student(int num, String name) {
    super();
    this.num = num;
    this.name = name;
}

public String toString() {
    return "Student [num=" + num + ", name=" + name + "]";
}

public int getNum() {
    return num;
}
public void setNum(int num) {
    this.num = num;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}

} }

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

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