Reputation: 2396
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
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
Reputation: 1074
Haven't closed the writer try it in finally.
finally {
writer.close();
}
Upvotes: 0
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