Question

This method should write random chars, but it doesn't write anything at all. I'm probably doing something stupidly wrong here, but for the life of me I can't find it.

public void writeRandomChunk(String fileName) {
    try {
        File saveFile = new File(folderName + '/' + fileName);

        PrintWriter writer = new PrintWriter(
                             new BufferedWriter(
                             new FileWriter(saveFile)));

        Random r = new Random(System.currentTimeMillis());

        for (int i = 0; i < chunkSize; i++) {
            for (int j = 0; j < chunkSize; j++) {
                writer.print((char)(r.nextInt(26) + 'a'));
            }
            writer.println();
        }

    } catch (Exception e) {
        System.out.println("Error in WorldFile writeRandomFile:\n"
                           + e.getLocalizedMessage());
    }
}
Was it helpful?

Solution

As with any stream (and this applies to most any language), you need to close it when you are done.

Streams are optimized to be fast, and as a consequence, not all of the data you write to them instantly appears in the file. When you close() or flush() a stream, the data is written to the file (or whatever other storage mechanism you are using).

In your case, try the following, instead.

public void writeRandomChunk(String fileName) {
    PrintWriter writer = null;
    try {
        File saveFile = new File(folderName + '/' + fileName);
        writer = new PrintWriter(
                             new BufferedWriter(
                             new FileWriter(saveFile)));

        Random r = new Random(System.currentTimeMillis());

        for (int i = 0; i < chunkSize; i++) {
            for (int j = 0; j < chunkSize; j++) {
                writer.print((char)(r.nextInt(26) + 'a'));
            }
            writer.println();
        }

    } catch (Exception e) {
        System.out.println("Error in WorldFile writeRandomFile:\n"
                           + e.getLocalizedMessage());
    } finally {
        if (writer != null)
            writer.close();
    }
}

OTHER TIPS

You need to flush() and/or close() the file at some point.

Haven't closed the writer try it in finally.

finally  {
  writer.close();
}

you should always close your stream. try this pattern with writers:

PrinterWriter writer = null;
try {
    writer = new PrinterWriter(...);
    // do your write loop here.
} catch (Exception e) {
    // recover from exception.
} finally {
    if (writer != null) {
        writer.close();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top