尽管我增加了项目的内存,但以下函数遇到了java.lang.OutOfMemoryError。
这发生在sb.append(CostMatrix[k][j]);
我想原因是写入文件效率低下。与其将所有数据存储在CostMatrix中,不如每次更新sb逐行写入文件可能会更好。如何实现呢?

private static void saveDistanceMatricesToCSV(int i, List<Object[]> data)
{
    System.out.println("Saving distance matrix " + i + " to CSV");
    try
    {
        String NEW_LINE = System.getProperty("line.separator");
        File file = new File("clusters/d"+i+".csv");
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        StringBuilder sb = new StringBuilder();

        int len = data.size();
        double[][] CostMatrix = new double[len][len];
        for (int k=0; k<len; k++)
        {
            for (int j=k; j<len; j++)
            {
                double lat1 = (Float) data.get(k)[3];
                double lon1 = (Float) data.get(k)[4];
                double lat2 = (Float) data.get(j)[3];
                double lon2 = (Float) data.get(j)[4];
                double dist = distfunc(lat1,lon1,lat2,lon2);
                CostMatrix[k][j] = dist;
                CostMatrix[j][k] = dist;
            }
        }

        for (int k=0; k<len; k++)
        {
            for (int j=0; j<len; j++)
            {
                sb.append(CostMatrix[k][j]);
                sb.append(",");
            }
            sb.append(NEW_LINE);
        }
        bw.write(sb.toString());
        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

最佳答案

您可以使用PrintWriter

PrintWriter printWriter = new PrintWriter(file);


然后,无需附加到StringBuilder,只需将其打印到输出即可:

printWriter.println(NEW_LINE);

10-05 21:49