繁体   English   中英

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

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

假设输入的文件具有以下数据:

101 
alice
102
bob
103
smith

如程序中所示,所有这些数据都将存储到文本文件中,只需输入文本文件名并读取所有数据并显示即可。

我想将这两个数据(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));
        }
    }
}

由于您已经为学生创建了一个数组列表,因此您可以在文本阅读器中进行此操作(while循环):stu.add(new Student(num,name)); 它的作用是创建一个学生对象,并将其放置在文本文件中每条记录的arraylist内。

您的程序应返回错误,因为试图将Stringint放入ArrayList中。 同样,您仅遍历学生的ArrayList ,而不打印出来。 您的代码应如下所示。

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());
        }

    }
}

假设您的文件如下所示
101爱丽丝
102鲍勃
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();
}

输入第一个答案后,问题已编辑,现在您的文件看起来像
101
爱丽丝
102
鲍勃
103
史密斯

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

}

班级学生{

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