Lo vuoi capire che:
a) stai comunque ancora usando la concatenazione delle stringhe, che così in un loop è inefficiente.
b) non si dovrebbero fare catch con un banale return. Così, in generale, "zittisci" le eccezioni.
c) per fare calcoli sui tempi che siano un po' attendibili, bisognerebbe ripetere il codice un po' di volte e prendere almeno la media dei tempi.
?
Ti spiace provare esattamente questo:
codice:
import java.io.*;
import java.nio.file.*;
public class ProvaTempiScritturaMatrice {
public static void main(String[] args) {
int righe = 600;
int colonne = 600;
final Object[][] matrice = new Object[righe][colonne];
for (int i = 0; i < righe; i++) {
for (int j = 0; j < colonne; j++) {
matrice[i][j] = "Indici della cella della matrice: i = " + i
+ " j = " + j;
}
}
Runnable andbinCode = new Runnable() {
public void run() {
try {
writeMatrix("prova.csv", matrice);
} catch (IOException e) {
System.out.println(e);
}
}
};
Runnable gianninoCode = new Runnable() {
public void run() {
Stampa2(matrice, "prova.csv");
}
};
System.out.println("andbin code : " + timeTest(andbinCode) + " millisecondi");
System.out.println("giannino code : " + timeTest(gianninoCode) + " millisecondi");
}
public static double timeTest(Runnable r) {
int count = 100;
double milliSum = 0;
for (int i = 0; i < count; i++) {
long begin = System.nanoTime();
r.run();
long end = System.nanoTime();
milliSum += (end - begin) / 1000000.0;
}
return milliSum / count;
}
/*---- andbin ----*/
public static void writeMatrix(String filename, Object[][] matrix) throws IOException {
FileOutputStream fos = new FileOutputStream(filename);
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(osw);
try {
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[r].length; c++) {
if (c > 0) {
bw.write(",");
}
bw.write(String.valueOf(matrix[r][c]));
}
bw.newLine();
}
} finally {
try { bw.close(); } catch (IOException e) {}
}
}
/*---- giannino1995 ----*/
static void Stampa2(Object[][] matrice, String nome_file) {
String lineSeparator = System.getProperty("line.separator");
try (OutputStream fout = new BufferedOutputStream(
Files.newOutputStream(Paths.get(nome_file)))) {
for (int i = 0; i < matrice.length; i++) {
for (int j = 0; j < matrice[0].length; j++) {
if (j < matrice[0].length - 1) {
fout.write((matrice[i][j] + ",").getBytes());
}
if (j == matrice[0].length - 1) {
fout.write((matrice[i][j] + lineSeparator).getBytes());
}
}
}
} catch (InvalidPathException e) {
return;
} catch (IOException e) {
return;
}
}
}
e dirmi l'output che ottieni?