如何用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 aNoSuchElementExceptionif the empty line is near the end of the file. - Automatic resource management: The try-with-resources block closes the
Scannerautomatically, so no need for manualclose()calls.
How It Works
- The
Scannerreads lines one by one from the file. - If a line is empty (or only whitespace), it skips the next two lines (if they exist).
- If the line is non-empty, it adds the line directly to the
ArrayList. - Any file reading errors are caught and reported with a message (plus optional stack trace for debugging).
内容的提问来源于stack exchange,提问作者Emely h
相关产品推荐
相关产品推荐

