Java 从文件读取时忽略所有空行

Java 从文件读取时忽略所有空行,java,regex,string,Java,Regex,String,我目前正在尝试获取一个大文本,并将文本逐句拆分。我有代码将文本分割成单独的句子,当然也包括空格。我需要向代码中添加什么,以使其省略句子数组中的空格 String [] sentence ArrayList <String> sentenceList = new ArrayList <String> (); try { Scanner sentenceScanner = new Scanner (new File("data/" +

我目前正在尝试获取一个大文本,并将文本逐句拆分。我有代码将文本分割成单独的句子,当然也包括空格。我需要向代码中添加什么,以使其省略句子数组中的空格

    String [] sentence
    ArrayList <String> sentenceList = new ArrayList <String> ();
    try {
        Scanner sentenceScanner = new Scanner (new File("data/" + fileName));
        while (sentenceScanner.hasNextLine()) {
            sentenceList.add (sentenceScanner.nextLine());
        }
        sentenceScanner.close();
    } catch (FileNotFoundException e) {
        System.out.println ("File Not Found");
    }

    for (int r = 0; r < sentenceArray.length; r++) {
        sentence = sentenceArray [r].split ("(?<=[.!?])\\s*");
        for (int i = 0; i < sentence.length; i++) {
            System.out.println (sentence [i]);
        }
    }
String[]句
ArrayList语句列表=新的ArrayList();
试一试{
Scanner语句Scanner=new Scanner(新文件(“数据/”+文件名));
while(sentenceScanner.hasNextLine()){
sentenceList.add(sentenceScanner.nextLine());
}
sentenceScanner.close();
}catch(filenotfounde异常){
System.out.println(“未找到文件”);
}
for(int r=0;r语句=语句数组[r]。拆分((?最好在读取输入数据时进行筛选:

while (sentenceScanner.hasNextLine()) {
    String line = sentenceScanner.nextLine().trim();
    if (!line.isEmpty()) {
        sentenceList.add (line);
    }
}

List-sentenceList;try(Stream-lines=Files.lines(Path.of(“data”,fileName)){sencenceList=lines.filter(s->!s.isBlank()).collect(Colelctors.toList());}
@JohannesKuhn这最好作为答案发布。您应该使用try-with-resources语句(或finally块)确保扫描仪已关闭。谢谢!请客:)