此方法应该写随机字符,但它根本不写任何内容。我可能在这里做了一些愚蠢的错误,但对于我的生活,我找不到它。
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());
}
}
答案 0 :(得分:4)
与任何流一样(这适用于大多数语言),您需要在完成后关闭它。
Streams被优化为快速,因此,并非您写入它们的所有数据都会立即显示在文件中。当您close()
或flush()
流时,数据将写入文件(或您正在使用的任何其他存储机制)。
在您的情况下,请尝试以下操作。
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();
}
}
答案 1 :(得分:1)
您需要在某个时刻刷新()和/或关闭()文件。
答案 2 :(得分:0)
没有关闭作家最终尝试。
finally {
writer.close();
}
答案 3 :(得分:0)
你应该总是关闭你的流。与作家一起尝试这种模式:
PrinterWriter writer = null;
try {
writer = new PrinterWriter(...);
// do your write loop here.
} catch (Exception e) {
// recover from exception.
} finally {
if (writer != null) {
writer.close();
}
}