简体   繁体   中英

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:

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)); what it does is you are creating an object of student and placing it inside the arraylist for every record in your text file.

Your program should return an error because are attempting to put a String and int into an ArrayList of Students. Also, you only iterates through your ArrayList of students and do not print them out. 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
102 bob
103 smith

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
alice
102
bob
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;
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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