我正在开发一个学校项目,在Java
中有一个简单的备份和恢复类。它有两种方法,一种用于备份,另一种用于还原,将文件分解为由程序确定的大小的块,并使用还原从这些块重建文件。
具体来说,我被困在恢复部分:
我想将每个块添加到一起并重新创建备份的初始文件。实际上,这会导致FileNotFound异常,说无法找到filename.pdf.0。但是,正如你在我的while循环中看到的那样,当文件编号等于或小于0时,我将其设置为中断。你能帮我理解为什么我会收到此错误以及如何修复它?
这是我的代码:
public static int restore(String filename, int numberOfPieces) throws Exception {
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(filename));
BufferedInputStream input = new BufferedInputStream(new FileInputStream(filename + "." + numberOfPieces));
while (numberOfPieces > 0) {
if (input.available() == 0) {
input.close();
numberOfPieces--;
input = new BufferedInputStream(new FileInputStream(filename + "." + numberOfPieces));
}
output.write(input.read());
}
output.close();
input.close();
return filename.length();
}
谢谢!
感谢Randal4的评论让我朝着正确的方向发展,我能够通过这个不那么优雅的解决方案来解决这个问题:
public static int restore(String filename, int numberOfPieces) throws Exception {
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(filename));
BufferedInputStream input = new BufferedInputStream(new FileInputStream(filename + "." + numberOfPieces));
while (numberOfPieces > 0) {
output.write(input.read());
if (input.available() == 0) {
input.close();
numberOfPieces--;
if (numberOfPieces > 0)
input = new BufferedInputStream(new FileInputStream(filename + "." + numberOfPieces));
}
}
output.close();
input.close();
return filename.length();
}
但是:现在尝试恢复原始文件时出现损坏的文件错误。哪里哪里。