You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Java Scanner读取文件到ArrayList并跳过指定行?

Solution: Read File to ArrayList with Empty Line Skip Logic

Hey Emely! Let's get your code working correctly for reading a file into an ArrayList while skipping empty lines and the next two lines whenever an empty line is found. Your current code has a small issue with how it consumes lines from the Scanner, which leads to missing content—let's fix that step by step.

What's Wrong with the Original Code?

The main problem is that you're calling scan1.nextLine() twice in each loop iteration (once to check if it's empty, then again in the else block). This means you're skipping every other non-empty line without adding it to the list. Also, you don't need to manually call scan1.close() when using try-with-resources—it handles that automatically.

Fixed Code

import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;

public class Einlesen {
    public static void main(String[] args) {
        ArrayList<String> wörter = new ArrayList<>();
        // Replace with your actual file path
        String filePath = "C:\\Users\\emely\\OneDrive - bwedu\\1Learn from the movies\\Pr_I_App\\Teil1.txt";

        try (Scanner scan1 = new Scanner(new File(filePath))) {
            while (scan1.hasNextLine()) {
                String currentLine = scan1.nextLine();
                
                // Check if current line is empty or only whitespace
                if (currentLine.trim().isEmpty()) {
                    // Skip the next two lines, but first check if they exist to avoid exceptions
                    if (scan1.hasNextLine()) {
                        scan1.nextLine(); // Skip first line after empty
                    }
                    if (scan1.hasNextLine()) {
                        scan1.nextLine(); // Skip second line after empty
                    }
                } else {
                    // Add non-empty line to the list
                    wörter.add(currentLine);
                    // Optional: Print the line to verify
                    System.out.println(currentLine);
                }
            }
        } catch (Exception e) {
            System.out.println("读取失败: " + e.getMessage());
            e.printStackTrace(); // Optional: For detailed error info
        }

        // Optional: Verify the list content
        System.out.println("\nFinal ArrayList content:");
        for (String line : wörter) {
            System.out.println(line);
        }
    }
}

Key Improvements Explained

  • Avoid line skipping bugs: We read the current line once into a variable first, so we don't accidentally consume extra lines with multiple nextLine() calls.
  • Robust empty line check: Using currentLine.trim().isEmpty() catches both completely empty lines and lines with only spaces/tabs, which is more thorough than checking for an empty string alone.
  • Prevent exceptions: Before skipping the next two lines, we check if scan1.hasNextLine() exists—this stops the code from throwing a NoSuchElementException if the empty line is near the end of the file.
  • Automatic resource management: The try-with-resources block closes the Scanner automatically, so no need for manual close() calls.

How It Works

  1. The Scanner reads lines one by one from the file.
  2. If a line is empty (or only whitespace), it skips the next two lines (if they exist).
  3. If the line is non-empty, it adds the line directly to the ArrayList.
  4. Any file reading errors are caught and reported with a message (plus optional stack trace for debugging).

内容的提问来源于stack exchange,提问作者Emely h

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 13:32:30