Java读取文本文件:将每行存入数组/二维double数组时无法拆分行求助
Hey there! Let's tackle these file reading issues step by step—they're super common when working with text files in Java, so you're not alone here.
If you're struggling to split lines, the most likely culprit is an incorrect reading method—like using Scanner.next() (which splits on whitespace, not newlines) or failing to loop through all lines. Here are two solid solutions:
Option 1: Use BufferedReader (Traditional & Flexible)
This approach gives you full control and handles line breaks automatically:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class LinesToArray { public static void main(String[] args) { List<String> linesList = new ArrayList<>(); // Try-with-resources auto-closes the stream to avoid leaks try (BufferedReader br = new BufferedReader(new FileReader("your-file-path.txt"))) { String currentLine; // Read line by line until we hit the end of the file while ((currentLine = br.readLine()) != null) { linesList.add(currentLine); } // Convert the list to a String array String[] linesArray = linesList.toArray(new String[0]); // Test the output for (String line : linesArray) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } }
The key here is br.readLine(), which reads an entire line at a time, ignoring newline characters—perfect for splitting your file into individual lines.
Option 2: Use Files.readAllLines() (Java 8+ Minimalist Approach)
If you're on Java 8 or newer, this one-liner does all the heavy lifting for you:
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; public class LinesToArray { public static void main(String[] args) { try { List<String> linesList = Files.readAllLines(Paths.get("your-file-path.txt")); String[] linesArray = linesList.toArray(new String[0]); // Test the output for (String line : linesArray) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } }
This method handles line breaks and stream cleanup internally, making your code concise and clean.
For this task, we need to: read each line → split the line into individual number strings → convert them to doubles → store in a 2D array. Let's assume your file looks something like this (numbers separated by spaces):
1.5 2.7 3.9 4.2 5.4 6.6 7.1 8.3 9.5
Here's a complete implementation:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Double2DArrayFromFile { public static void main(String[] args) { // Initialize a 2D array with 3 rows (since your file has 3 lines) double[][] doubleArray = new double[3][]; int rowIndex = 0; try (BufferedReader br = new BufferedReader(new FileReader("your-double-file.txt"))) { String currentLine; while ((currentLine = br.readLine()) != null && rowIndex < 3) { // Trim whitespace and split the line into number strings // Use "\\s+" to match any number of spaces/tabs String[] numberStrings = currentLine.trim().split("\\s+"); double[] row = new double[numberStrings.length]; // Convert each string to a double for (int i = 0; i < numberStrings.length; i++) { row[i] = Double.parseDouble(numberStrings[i]); } // Add the row to the 2D array doubleArray[rowIndex] = row; rowIndex++; } // Test the 2D array output for (double[] row : doubleArray) { for (double num : row) { System.out.print(num + " "); } System.out.println(); } } catch (IOException e) { e.printStackTrace(); } catch (NumberFormatException e) { System.err.println("Oops! Found a non-numeric value in the file."); e.printStackTrace(); } } }
A few critical notes here:
trim()removes leading/trailing whitespace to avoid empty strings during splittingsplit("\\s+")uses regex to handle any number of spaces or tabs between numbers (adjust tosplit(",")if your numbers are comma-separated)- We catch
NumberFormatExceptionto handle cases where the file has non-numeric content
Chances are your original code failed because you weren't reading lines correctly, or you messed up the splitting logic for the double values. Give these examples a shot—they should fix your issues!
内容的提问来源于stack exchange,提问作者Jane Brown

