Read data from a text file using Java

后端 未结 16 1538
挽巷
挽巷 2020-12-10 05:35

I need to read a text file line by line using Java. I use available() method of FileInputStream to check and loop over the file. But while reading,

16条回答
  •  时光取名叫无心
    2020-12-10 06:11

    In Java 8 you could easily turn your text file into a List of Strings with streams by using Files.lines and collect:

    private List loadFile() {
        URI uri = null;
        try {
            uri = ClassLoader.getSystemResource("example.txt").toURI();
        } catch (URISyntaxException e) {
            LOGGER.error("Failed to load file.", e);
        }
        List list = null;
        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;
    }
    

提交回复
热议问题