我的文件保存逻辑是否正确?

时间:2017-12-02 00:07:59

标签: java file

我的java应用程序调用一个rest端点,在响应体中是一个10GB的XML文件。在我发送其余任务之前,我会询问服务文件中有多少条记录。然后我检索文件。当我运行我的应用程序时,文件已成功保存,但只有大约50%的预期记录。文件没有所有记录有两个原因:

  1. 从其余端点发送的文件只有50%的预期记录
  2. 我的应用程序在下载完成之前就已经崩溃了
  3. 我的问题是,如果在方案2中我的应用程序崩溃了,我会看到一个例外情况吗?我没有看到异常,事实上,在保存保存后我看到了我的日志语句,说“文件已成功保存”。

    编辑:我已经通过卷曲请求在我的应用程序之外下载了文件,同样的事情发生了 - 只有50%的预期人口被下载了。这证明问题不在于我的文件保存逻辑。

    public void saveFile() {
        try {
            downloadAndSaveFile();
        } catch (Exception e) {
            LOGGER.error("A error has occurred processing all content, caused by {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
    
    private void downloadAndSaveFile() throws Exception {
        long recordCount = countRecords();
        LOGGER.info("Number of records to process is {}", recordCount);
    
        if (recordCount > 0 ) {
            InputStream dataToSave = getAllContent();
            saveStream(dataToSave);
            LOGGER.info("File successfully saved.");
        } else {
            LOGGER.error("No content to retrieve");
            throw new RuntimeException("There are no records to process");
        }
    }
    
    
    public InputStream getAllContent() throws Exception {
        return callRestEndpoint(webTarget).readEntity(InputStream.class);
    }
    
    private Response callRestEndpoint(WebTarget target) throws InterruptedException {
        Response response = null;
    
        for (int numberOfTries = 0; numberOfTries < reconnectRetries; numberOfTries++) {
            try {
                response = makeGetRequest(target);
    
                if (OK.getStatusCode() == response.getStatus()) {
                    break;
                }
    
            } catch (Exception ex) {
                retryRequest(numberOfTries, ex);
            }
        }
    
        return response;
    }
    
    public void saveStream(InputStream inputStream) throws IOException {
        File fileToCreate = new File(fileName);
    
        if (!fileToCreate.exists()) {
            fileToCreate.mkdirs();
        }
    
        Files.copy(
                inputStream,
                fileToCreate.toPath(),
                StandardCopyOption.REPLACE_EXISTING
        );
    
        closeQuietly(inputStream);
    }
    

1 个答案:

答案 0 :(得分:0)

  

我的文件保存逻辑是否正确?

没有

if (!fileToCreate.exists()) {
    fileToCreate.mkdirs();
}

在这里,您将fileToCreate中的每个元素创建为目录,包括最终元素。因此,稍后尝试打开文件将失败。 exists()测试毫无意义。它应该是:

fileToCreate.getParentFile().mkdirs();
  

如果在方案2中我的应用程序崩溃了,我会看到一个例外情况吗

是的,前提是您在某处打印或登录。该方法肯定会抛出一个。

相关问题