Java问题:无法输出全部内容到文本文件且触发数组越界异常
Hey there! Let's tackle your two Java issues one by one. I'll break down the possible causes and show you actionable fixes based on the code snippets you shared.
From what I can see, the most common reasons for this issue are related to how you're managing your BufferedWriter stream:
- Forgot to flush/close the stream: Buffered writers store data in memory (a buffer) before writing to disk. If you don't call
flush()orclose(), some content might never get written. - Overwriting the file instead of appending: If you create a new
FileWriterinside your loop without enabling append mode, each iteration will overwrite the previous content instead of adding to it. - Unclosed streams due to exceptions: If an error occurs mid-execution, your code might skip the
close()call, leaving unwritten data in the buffer.
Fix: Use Try-With-Resources (Recommended)
Java 7+ has a built-in try-with-resources feature that automatically closes streams, even if an exception occurs. It also ensures all buffered data is flushed to disk. Here's how to adjust your code:
package Test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; public class TestCode { public static void main(String[] args) throws IOException { // Use try-with-resources for both reader and writer to auto-manage streams String outputPath = "C:\\Users\\Dell\\Desktop\\output.txt"; try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputPath, true))) { // "true" enables append mode File dir = new File("C:\\Users\\Dell\\Desktop\\testing\\"); // Add a check to avoid null pointer if the directory is invalid File[] files = dir.listFiles(); if (files == null) { System.err.println("Invalid directory path or no files found"); return; } for (File file : files) { HashMap<String, String> map = new HashMap<>(); try (BufferedReader reader = new BufferedReader(new FileReader(file))) { String line; while ((line = reader.readLine()) != null) { // Process your line and add to map map.put("sampleKey", line); // Write to output file writer.write(line); writer.newLine(); // Add a newline after each line } } // Reader is auto-closed here, no need for manual close } } catch (IOException e) { e.printStackTrace(); // Handle exceptions properly in production code } // Writer is auto-closed and flushed here } }
This error happens when you try to access an array index that doesn't exist (e.g., an array of length 2, but you try to access index 2). Based on your code context, this is almost certainly caused by:
- Splitting a string into an array (e.g.,
line.split(",")) and assuming every line has enough elements, but some lines are malformed (missing delimiters).
Fix: Add Length Checks Before Accessing Array Indices
Always validate the length of the array before accessing specific indices. Here's how to adjust your line-processing logic:
while ((line = reader.readLine()) != null) { // Skip empty lines to avoid unnecessary processing if (line.trim().isEmpty()) { continue; } String[] lineParts = line.split(","); // Adjust delimiter to match your data // Check if the array has enough elements before accessing indices if (lineParts.length >= 2) { String key = lineParts[0].trim(); String value = lineParts[1].trim(); map.put(key, value); } else { // Log or handle malformed lines instead of crashing System.err.println("Skipping malformed line: " + line); } }
Bonus Tip:
If you're working with fixed-format data, consider using a library like Apache Commons CSV to handle parsing more robustly, which reduces the chance of index errors.
内容的提问来源于stack exchange,提问作者Hustler

