Java reading a file into an ArrayList?

后端 未结 13 1145
醉话见心
醉话见心 2020-11-22 12:05

How do you read the contents of a file into an ArrayList in Java?

Here are the file contents:

cat
ho         


        
13条回答
  •  一生所求
    2020-11-22 13:01

    In Java 8 you could use streams and Files.lines:

    List list = null;
    try (Stream lines = Files.lines(myPathToTheFile))) {
        list = lines.collect(Collectors.toList());
    } catch (IOException e) {
        LOGGER.error("Failed to load file.", e);
    }
    

    Or as a function including loading the file from the file system:

    private List loadFile() {
        List list = null;
        URI uri = null;
    
        try {
            uri = ClassLoader.getSystemResource("example.txt").toURI();
        } catch (URISyntaxException e) {
            LOGGER.error("Failed to load file.", e);
        }
    
        try (Stream lines = Files.lines(Paths.get(uri))) {
            list = lines.collect(Collectors.toList());
        } catch (IOException e) {
            LOGGER.error("Failed to load file.", e);
        }
        return list;
    }
    

提交回复
热议问题