简体   繁体   English

如何将 txt 读取到 arrayList 然后返回 arrayList?

[英]How to read txt to arrayList then return arrayList?

I need to read a file into an arrayList and return the arrayList but I'm having difficulty putting into an object.我需要将文件读入 arrayList 并返回 arrayList 但我很难放入 object。 I keep getting this error:我不断收到此错误:

Type mismatch: cannot convert from ArrayList to ArrayList类型不匹配:无法从 ArrayList 转换为 ArrayList

*Not allowed to change the method *不允许更改方法

I've tried putting the ArrayList inside ArrayList我试过把 ArrayList 放在 ArrayList 里面

public static ArrayList<Names> readEntrees(String fileName) {
    String filename = "data/names.txt";

    ArrayList<String> myNames = new ArrayList<String>();

    try {
    BufferedReader br = new BufferedReader(new FileReader("names.txt"));

    String line = null;

    while ((line = br.readLine()) != null) {
        //take each line and split them around @@
        String[] elements = line.split("@@");
        //convert the string[] to an arraylist
        myNames = new ArrayList< String>(Arrays.asList(elements));
        myNames.add(line);
    }

    br.close();
    return (myNames);
}

Type mismatch: cannot convert from ArrayList to ArrayList类型不匹配:无法从 ArrayList 转换为 ArrayList

You need to convert a List of String to a List of Names.您需要将字符串列表转换为名称列表。 So, let's use a simple Name class (I have to make this up since I don't have your class code):所以,让我们使用一个简单的名称 class (我必须弥补这个,因为我没有你的 class 代码):

public class Name {
    String name;

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

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Name [name=" + name + "]";
    }    
}

Here we can convert a String to a Name object using the new Name(text) constructor.在这里,我们可以使用new Name(text)构造函数将 String 转换为 Name object。 So let's let your method return a List<Name> , not an ArrayList<Name> as the former will do all that the latter will do but with more flexibility (code to the interface,... etc), then using Streams, we can convert the String data into a List<Name> :因此,让我们让您的方法返回List<Name> ,而不是ArrayList<Name> ,因为前者将完成后者将做的所有事情,但具有更大的灵活性(接口代码等),然后使用 Streams,我们可以将 String 数据转换为List<Name>

public static List<Name> readEntries(String filename) throws IOException {

    // String filename = "data/names.txt"; // this makes **no sense**. get rid of it

    List<Name> result = null;
    // code to read in text
    File file = new File(filename);
    result = Files.lines(file.toPath()).map(Name::new).collect(Collectors.toList());

    return result;
}

Code corrected to split each line using "@@" , and improved as per AjahnCharles :代码更正为使用"@@"分割每一行,并根据AjahnCharles进行了改进:

public static List<Name> readEntries(String filename) throws IOException {
    List<Name> result = null;
    // code to read in text
    result = Files.lines(Paths.get(filename)) // get each line from file
            .flatMap(Pattern.compile("@@")::splitAsStream) // split each line into stream
            .map(Name::new) // map each String into Name
            .collect(Collectors.toList()); // collect into List

    return result;
}

Tester program:测试程序:

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

public class TestNameList {
    public static void main(String[] args) {
        // TODO: use actual path String to file
        String fileName = "src/pkg3/Names.txt";
        try {
            List<Name> names = readEntries(fileName);
            names.stream().forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static List<Name> readEntries(String filename) throws IOException {
        List<Name> result = null;
        // code to read in text
        result = Files.lines(Paths.get(filename)) // get each line from file
                .flatMap(Pattern.compile("@@")::splitAsStream) // split each line into stream
                .map(Name::new) // map each String into Name
                .collect(Collectors.toList()); // collect into List

        return result;
    }
}

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

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