我已将其减少到最低限度,似乎无法解决问题。我已经做了很多询问,并尝试了无数次迭代。因此,任何建议将不胜感激。我使用了for循环来查看希望从输入文件中获取的数组输出(只是数字列表;行的范围是1位数到6位数)。理想情况下,需要将行以int的方式读入数组。非常感谢!
public static void main(String[] args) throws IOException {
String line = "";
int matrix[][] = new int[0][];
String text = "line1\n\n\nline4";
int lineNumber = 0;
try {
FileReader fileReader = new FileReader("input.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((bufferedReader.readLine() != null)) {
String stringArray[] = line.split(" ");
for(int x = 0; x <= stringArray.length-1; x++) {
System.out.println(stringArray[x]);
System.out.printf("%04d: %s%n", ++lineNumber, line);
System.out.println("here");
}
}
} catch(IOException e){
e.printStackTrace();
}
}
}
输出片段:
0001: 这里
0002: 这里
0003: 这里
答案 0 :(得分:0)
如果您打算以矩阵形式读取文件(每行一个单独的整数数组),则此方法可能会有所帮助:
/**
* Read a matrix from the specified path, each line corresponds to a
* separate array of integers.
*
* @param path the path to the file, not null
* @return a matrix, not null
* @throws IOException if an I/O error occurs opening the file
* @throws NumberFormatException if the file contains non-parsable integers
*/
public static int[][] readMatrix(Path path) throws IOException
{
Objects.requireNonNull(path);
try (Stream<String> lines = Files.lines(path))
{
return lines
.map(String::trim) // Remove leading and trailing whitespaces.
.filter(line -> !line.isEmpty()) // Ignore empty lines.
.map(line -> line.split("\\s+")) // Split line by whitespaces.
// Map tokens of type String[] to int[]
.map(tokens -> Arrays.stream(tokens)
.mapToInt(Integer::parseInt) // Throws NumberFormatException if not parsable
.toArray())
.toArray(int[][]::new);
} catch (UncheckedIOException e)
{
throw e.getCause();
}
}
如果您只对整数数组感兴趣,并且不关心按行分割它们:
Files.lines()
.map(String::trim)
.filter(line -> !line.isEmpty())
.map(line -> line.split("\\s+"))
.flatMapToInt(tokens -> Arrays.stream(tokens)
.mapToInt(Integer::parseInt))
.toArray();