您好!您提到的Matrix txt文件是一种文本文件,其中包含矩阵数据。要将其读取并存储为数组,您可以使用以下方法:
def read_matrix_file(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
matrix = []
for line in lines:
row = [int(x) for x in line.strip().split()]
matrix.append(row)
return matrix
file_path = 'matrix.txt'
matrix = read_matrix_file(file_path)
print(matrix)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MatrixReader {
public static void main(String[] args) {
String filePath = "matrix.txt";
int[][] matrix = readMatrixFile(filePath);
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
public static int[][] readMatrixFile(String filePath) {
List<int[]> matrixList = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
String[] elements = line.trim().split("\\s+");
int[] row = new int[elements.length];
for (int i = 0; i< elements.length; i++) {
row[i] = Integer.parseInt(elements[i]);
}
matrixList.add(row);
}
} catch (IOException e) {
e.printStackTrace();
}
int[][] matrix = new int[matrixList.size()][];
return matrixList.toArray(matrix);
}
}
这些代码示例将读取Matrix txt文件并将其存储为数组。请注意,这些示例仅适用于整数矩阵。如果您的矩阵包含其他类型的数据,例如浮点数或字符串,则需要相应地修改代码。
领取专属 10元无门槛券
手把手带您无忧上云