suddjian
suddjian

Reputation: 2396

Why isn't my file write method working?

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());
    }
}

Upvotes: 0

Views: 2905

Answers (4)

kel c.
kel c.

Reputation: 323

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();
    }
}

Upvotes: 0

neo
neo

Reputation: 1074

Haven't closed the writer try it in finally.

finally  {
  writer.close();
}

Upvotes: 0

rob
rob

Reputation: 6247

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

Upvotes: 1

cheeken
cheeken

Reputation: 34655

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();
    }
}

Upvotes: 4

Related Questions