在我的Java程序中,我想显示移动文件的进度。我使用以下代码片段来复制文件,这允许我跟踪复制的字节并在进度条中显示它。我想知道代码是否适合移动文件而不是复制它们?
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile));
int theByte;
while((theByte = bis.read()) != -1)
{
bos.write(theByte);
}
bis.close();
bos.close();
答案 0 :(得分:1)
好的,所以“移动”操作是最后带有“删除”的副本,例如......
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(sourceFile));
bos = new BufferedOutputStream(new FileOutputStream(targetFile));
int theByte;
while((theByte = bis.read()) != -1)
{
bos.write(theByte);
}
bos.close();
bis.close();
// You may want to verify that the file's are the same (ie the file size for example)
if (!sourceFile.delete()) {
throw new IOException("Failed to remove source file " + sourceFile);
}
} catch (IOException exp) {
exp.printStackTrace();
} finally {
try {
bis.close();
} catch (Exception exp) {
}
try {
bos.close();
} catch (Exception exp) {
}
}