如何读取包含文本和整数的文件并将整数保存在数组列表中

时间:2017-01-17 14:28:02

标签: java java-8

我有一个文本文件,我称之为read_me2(link):

!This is for testing the ability to read a file
1 3 
4 5
6 7
8 9
1
2
3
4
5 6 4

我想读取它并使用Java 8功能将数据存储在整数列表中。到目前为止,我能够做到这一点,但我认为这种方式不是最理想的。你能给我一些帮助吗?下面,请找到我的代码:

    //This is my package
    package ReadAFile;

        // Modified http://www.mkyong.com/java8/java-8-stream-read-a-file-line-by-line/

        import java.io.IOException;
        import java.nio.file.Files;
        import java.nio.file.Paths;
        import java.util.ArrayList;
        import java.util.List;
        import java.util.stream.Collectors;
        import java.util.stream.Stream;


        public class ReadAndStoreFileContents {

            public static void main(String[] args) {

                List<String> list2 = new ArrayList<>(); 

String fileName2 = "/Users/riccardo/Dropbox/A-Data/JavaSandBox/read_me2.txt";   
                try (Stream<String> stream = Files.lines(Paths.get(fileName2))) {
                    list2 = stream.
                            filter(line -> !line.startsWith("!")).
                            collect(Collectors.toList());
                } catch (IOException e) { 
                    e.printStackTrace();
                }


    //          This will be certainly not optimal because I m reading the List a second time           

                List<Integer> intList = new ArrayList<>();  

                for(String string : list2){
                    for(String retval: string.split(" ")){
                        intList.add(Integer.valueOf(retval));
                    }
                    System.out.println(intList.toString());
                }


            }

        }

感谢您的时间,

riccardo

1 个答案:

答案 0 :(得分:1)

由于文件中有Stream个字符串,您可以将它们平面映射到单个字符串,然后将它们映射到Integers,然后收集并打印出来:

try (Stream<String> stream = Files.lines(Paths.get(fileName2))) {
                        list2 = stream
                                .filter(line -> !line.startsWith("!"))
                                .flatMap(line -> line.split(" ").stream())
                                .map(Integer::valueOf)
                                .collect(Collectors.toList());
                    } catch (IOException e) { 
                        e.printStackTrace();
                    }