0

您能否建议如何处理这些情况?我知道在第二个例子中,它很少发生在 unix 上,是吗?如果访问权限没问题。该文件甚至不会被创建。我不明白为什么 IOException 存在,无论它是否被创建,我们为什么要打扰 IOException ?

但在第一个例子中,会有一个损坏的僵尸文件。现在如果你告诉用户再次上传它,同样的事情可能会发生。如果你不能这样做,并且输入流没有标记。你丢失了你的数据?我真的不喜欢在 Java 中如何做到这一点,我希望 Java 7 中的新 IO 更好

删除它是不是很正常

public void inputStreamToFile(InputStream in, File file) throws SystemException {

    OutputStream out;
    try {
        out = new FileOutputStream(file);
    } catch (FileNotFoundException e) {
        throw new SystemException("Temporary file created : " + file.getAbsolutePath() + " but not found to be populated", e);
    }

    boolean fileCorrupted = false;
    int read = 0;
    byte[] bytes = new byte[1024];

    try {
        while ((read = in.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
    } catch (IOException e) {
        fileCorrupted = true;
        logger.fatal("IO went wrong for file : " + file.getAbsolutePath(), e);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);

                    if(fileCorrupted) {
        ???
                    }
    }
}


public File createTempFile(String fileId, String ext, String root) throws SystemException {

    String fileName = fileId + "." + ext;

    File dir = new File(root);

    if (!dir.exists()) {
        if (!dir.mkdirs())
            throw new SystemException("Directory " + dir.getAbsolutePath() + " already exists most probably");
    }

    File file = new File(dir, fileName);

    boolean fileCreated = false;
    boolean fileCorrupted = false;
    try {
        fileCreated = file.createNewFile();
    } catch (IOException e) {
        fileCorrupted = true;
        logger.error("Temp file " + file.getAbsolutePath() + " creation fail", e);
    } finally {

        if (fileCreated)
            return file;
        else if (!fileCreated && !fileCorrupted)
            throw new SystemException("File " + file.getAbsolutePath() + " already exists most probably");
        else if (!fileCreated && fileCorrupted) {

        }
    }

}
4

1 回答 1

1

我真的不喜欢在 Java 中如何做到这一点,我希望 Java 7 中的新 IO 更好

我不确定 Java 在您使用它的方式上与任何其他编程语言/环境有何不同:

  • 客户端通过网络向您发送一些数据
  • 阅读时,将其写入本地文件

无论语言/工具/环境如何,连接都可能中断或丢失、客户端消失、磁盘死机或发生任何其他错误。I/O 错误可能发生在任何环境中。

在这种情况下您可以做什么很大程度上取决于情况和发生的错误。例如,数据是否以某种方式结构化,例如,您可以要求用户从记录 1000 继续上传?但是,这里没有适合所有情况的单一解决方案。

于 2011-07-21T17:01:51.830 回答