
Macierze: użycie DataInput i DataOutput
Interfejsy DataOutput i DataInput są implementowane m.in. przez klasę RandomAccessFile.
Zapis macierzy
Do zapisu macierzy możemy użyć metody write z klasy MatrixUtil:
public static void write(double[][] array, DataOutput output) {
int rows = array.length;
int cols = array[0].length;
try {
output.writeInt(rows);
output.writeInt(cols);
for (double[] doubles : array) {
for (int j = 0; j <cols; j++) {
output.writeDouble(doubles[j]);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
Przykład w klasie Matrix043:
double[][] tabl = {{3, 2, 1}, {6, 5, 4}, {8, 9, 7}};
File file = new File("matrices/assets/matrix3.dat");
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(file, "rw");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
raf.seek(0);
} catch (IOException e) {
e.printStackTrace();
}
MatrixUtil.write(tabl, raf);
Po uruchomieniu kodu w folderze matrices/assets pojawi się plik matrix3.dat.
Odczyt macierzy
Do odczytania macierzy możemy użyć metody read z klasy MatrixUtil:
public static double[][] read(DataInput input) {
int rows;
int cols;
double[][] temp = null;
try {
rows = input.readInt();
cols = input.readInt();
temp = new double[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
temp[i][j] = input.readDouble();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return temp;
}
Przykłąd w klasie Matrix044:
double[][] tabl;
File file = new File("matrices/assets/matrix3.dat");
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(file, "rw");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
raf.seek(0);
} catch (IOException e) {
e.printStackTrace();
}
tabl = MatrixUtil.read(raf);
Matrix mat = new Matrix(tabl);
mat.printToConsole();
Po uruchomieniuu klasy na konsoli zobaczymy:
3.0 2.0 1.0 6.0 5.0 4.0 8.0 9.0 7.0
Pliki do ściągnięcia
Moduł matrices – aktualny stan projektu = 031;
