简体   繁体   English

为什么我的文件写入方法不起作用?

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

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). 当您close()flush()流时,数据将被写入文件(或您正在使用的任何其他存储机制)。

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

您需要在某个时候冲洗文件和/或关闭文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM