请求修复读取文本文件并解析至ArrayList的空行处理异常问题
Hey there! Let's break down why your current code is still hitting that empty string array issue, even with the if (line.isEmpty()) continue; check, and fix it step by step.
What's Causing the Problem?
Your debug info shows String[] words has a length of 1 with an empty string—this usually happens for two key reasons:
- Lines with only whitespace: The
isEmpty()check only catches completely blank lines (zero characters), but lines filled with spaces, tabs, or newline characters will slip through. Splitting these lines results in an array containing just an empty string. - Poor split logic: If you're using a simple split like
split(" "), consecutive spaces or leading/trailing spaces will create empty string elements in the resulting array.
Solution Steps
Since you can't use File or Object I/O streams, we'll stick with BufferedReader and InputStreamReader (for reading from classpath resources or input streams) to handle file reading, and adjust our line processing to eliminate empty elements entirely.
1. Filter Lines with Hidden Whitespace
Replace your basic isEmpty() check with a trim() first—this removes all leading/trailing whitespace characters, so lines that are just blank (even with invisible spaces) get filtered out properly:
String trimmedLine = line.trim(); if (trimmedLine.isEmpty()) { continue; }
2. Split Without Creating Empty Elements
Use a regex-based split to treat any number of whitespace characters as a single delimiter. This way, even if there are multiple spaces between words, you won't get empty strings in your array:
String[] words = trimmedLine.split("\\s+");
\\s+matches one or more whitespace characters (spaces, tabs, newlines)- This split ignores leading whitespace and collapses consecutive spaces into one separator, ensuring all elements in
wordsare non-empty.
Full Example Code
Here's how the corrected reading logic might look:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class FileReaderExample { public static void main(String[] args) { ArrayList<String> dataList = new ArrayList<>(); // Use InputStreamReader to avoid File class (read from classpath resource) try (BufferedReader reader = new BufferedReader( new InputStreamReader(FileReaderExample.class.getResourceAsStream("/your-file.txt")))) { String line; while ((line = reader.readLine()) != null) { // Trim and skip empty/whitespace-only lines String trimmedLine = line.trim(); if (trimmedLine.isEmpty()) { continue; } // Split into non-empty words String[] words = trimmedLine.split("\\s+"); // Add all valid words to the ArrayList for (String word : words) { dataList.add(word); } } } catch (IOException e) { e.printStackTrace(); } // Verify the result System.out.println("Data in ArrayList: " + dataList); } }
If You're Using a Non-Whitespace Delimiter
If you're splitting on something else (like commas), adjust the logic to clean each split part individually:
String[] parts = trimmedLine.split(","); for (String part : parts) { String cleanedPart = part.trim(); if (!cleanedPart.isEmpty()) { dataList.add(cleanedPart); } }
This ensures you don't add empty strings from consecutive delimiters (like ,,) or spaces around delimiters.
Why This Works
- The
trim()+isEmpty()check catches all lines that have no actual content, even if they're filled with invisible whitespace. - The regex split (or post-split cleaning) eliminates empty string elements before they can cause exceptions in your code.
内容的提问来源于stack exchange,提问作者fnklstn

