您能否建议如何处理这些情况?我知道在第二个例子中,在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) {
}
}
}
最佳答案
I really don't like how this is done in Java, I hope the new IO in Java 7 is better
我不确定 Java 与您使用的任何其他编程语言/环境有何不同:
- 客户端通过线路向您发送一些数据
- 当您读取它时,将其写入本地文件
无论使用哪种语言/工具/环境,连接都可能中断或丢失、客户端消失、磁盘损坏或发生任何其他错误。 I/O 错误可能发生在任何环境中。
在这种情况下您可以执行的操作很大程度上取决于具体情况和发生的错误。例如,数据是否以某种方式构建,您可以要求用户从记录 1000 继续上传?但是,没有一个解决方案可以满足所有情况。
关于java - 如何处理创建的损坏文件但发生 IOException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6779787/