Reading text file into arraylist

岁酱吖の 提交于 2019-12-19 04:02:00

问题


I really new to Java so I'm having some trouble figuring this out. So basically I have a text file that looks like this:

1:John:false  
2:Bob:false    
3:Audrey:false

How can I create an ArrayList from the text file for each line?


回答1:


Read from a file and add each line into arrayList. See the code for example.

public static void main(String[] args) {

        ArrayList<String> arr = new ArrayList<String>();
        try (BufferedReader br = new BufferedReader(new FileReader(<your_file_path>)))
        {

            String sCurrentLine;

            while ((sCurrentLine = br.readLine()) != null) {
                arr.add(sCurrentLine);
            }

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

    }



回答2:


While the answer above me works, here's another way to do it. Make sure to import java.util.Scanner.

public static void main(String[] args) {
     ArrayList<String> list = new ArrayList<String>();
     Scanner scan = new Scanner("YOURFILE.txt");
     while(scan.hasNextLine()){
         list.add(scan.nextLine());
     }
     scan.close();
}



回答3:


If you know how to read a file line by line, either by using Scanner or by using BufferedReader then reading a text file into ArrayList is not difficult for you. All you need to do is read each line and store that into ArrayList, as shown in following example:

BufferedReader bufReader = new BufferedReader(new 
FileReader("file.txt"));
ArrayList<String> listOfLines = new ArrayList<>);
String line = bufReader.readLine(); while (line != null)
{
    listOfLines.add(line);
    line = bufReader.readLine();
} 
bufReader.close();

Just remember to close the BufferedReader once you are done to prevent resource leak, as you don't have try-with-resource statement




回答4:


This will be help to you.

List<String> list = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("list.txt"));
String line;
while ((line = reader.readLine()) != null) {
    list.add(line);
}
reader.close();

Then you can access those elements in the arraylist.




回答5:


java 8 lets you do this

String fileName = "c://lines.txt";
        List<String> list = new ArrayList<>();

        try (Stream<String> stream = Files.lines(Paths.get(fileName))) {

            list = stream
                    .map(String::toUpperCase)
                    .collect(Collectors.toList());

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

        list.forEach(System.out::println);


来源:https://stackoverflow.com/questions/36440723/reading-text-file-into-arraylist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!