无限制地读取较大的文件而不会出错

时间:2018-03-15 06:18:54

标签: java

我是Java的菜鸟,所以可能会遗漏一些显而易见的东西但我有一个功能适用于200-300k范围内的文件文件而没有问题但是一旦我达到1.4mb它就会超过默默地

以下是代码:

t2

当它达到使其失败的大小阈值时,它似乎保持在 while 循环内或至少是我的假设,因为它确实向控制台报告“总文件大小为读...“它永远不会到达”文件内容已被读入“日志记录。

1 个答案:

答案 0 :(得分:1)

您正在循环中执行字符连接,从而创建许多临时String个对象。我会使用StringBuilder。我也更喜欢一个try-with-resources。如果可能的话,我更愿意直接从InputStream流向OutputStream(而不是将其完全读入内存)。无论如何,根据这里的内容,

private String readOutputFile(String filename) {
    if (filename == null) {
        return null;
    }
    File file = new File(filename);
    StringBuilder sb = new StringBuilder();
    this.logger.log("Reading " + filename + " from filesystem.");
    try (FileInputStream fis = new FileInputStream(file)) {
        System.out.println("Total file size to read (in bytes) : " + fis.available());
        int content;
        while ((content = fis.read()) != -1) {
            sb.append((char) content);
        }
    } catch (IOException e) {
        this.logger.log("IO Problem reading ITMS output file\n");
        e.printStackTrace();
        throw new Error("io-error/itms-output");
    }
    this.logger.log("File content has been read in");
    String compressed = this.compress(this.cleanXML(sb.toString()));
    this.logger.log("The compressed file size is : " + compressed.length() + " bytes");

    return compressed;
}