简体   繁体   English

Java:处理要从文件读取的流

[英]Java: Handling a stream to read from file

for a lab at my University I'm developing a system in Java that is able to store data from a file (given the file path as a String). 对于我大学的一个实验室,我正在用Java开发一个系统,该系统能够存储来自文件的数据(给定文件路径为String)。 I was trying to handle the problem using a stream of lines from the path, but I got stuck at an early stage. 我试图使用路径中的一行流来处理问题,但是我在早期阶段陷入了困境。 The file is organised as follow: the different fields of a line are separated by ";" 该文件的组织方式如下:一行的不同字段用“;”分隔。 and each line starts with a "P" or a "D". 每行以“ P”或“ D”开头。 Depending on this parameter, I'll use the contenent of the line to create a "Patient" object or a "Doctor" object, subsequently stored in two different maps (patients or doctors). 根据此参数,我将使用该行的内容来创建“患者”对象或“医生”对象,然后将其存储在两个不同的地图(患者或医生)中。 I did the following: 我做了以下工作:

Path p= Paths.get(path);
Stream <String> lines=Files.lines(p, StandardCharsets.UTF_8);
lines.flatMap(l->Stream.of(l.split("; ")))....

My idea was to check the word at the beginning of the line and, according to that, the remaining element would be used as parameter for a method able to create and store the corresponding object(insertPatient or insertDoctor). 我的想法是检查该行开头的单词,并据此将其余元素用作能够创建和存储相应对象(insertPatient或insertDoctor)的方法的参数。 But I haven't got the faintest idea of how to do that. 但是我还不知道如何做到这一点。 I know different way to do the same, but I really want to develop the solution using a stream, at least in the procedure of reading the different lines. 我知道有不同的方法可以做到这一点,但是我真的想至少在读取不同行的过程中使用流来开发解决方案。 Thanks, Gianluca. 谢谢,詹卢卡。

try (Stream<> lines = Files.lines(p, StandardCharsets.UTF_8)) { // 1
    lines.map(line -> line.split(";"))                          // 2
         .forEach(lineAsArray -> {
             if (lineAsArray[0].equals("D")) {
                 insertDoctor(lineAsArray);
             }
             else if (lineAsArray[0].equals("P")) {
                 insertPatient(lineAsArray);
             }
         });
}
  1. Use try-with-resources to make sure the stream, and thus the file reader, is closed 使用try-with-resources确保流以及文件阅读器已关闭
  2. Don't use flatMap, since you want to act on complete lines, and not on cells. 不要使用flatMap,因为您要对整行而不是对单元格进行操作。

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

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