JAVA.io文件剪切/删除问题
在实现文件剪切的过程中,我发现无法删除原文件。
FileOutputStream fos = null;
FileInputStream fis = null;
File file = null;
try{
file = new File("C:\\666.docx");
fis = new FileInputStream(file);
fos = new FileOutputStream("C:\\777.docx");
byte[] bytes = new byte[1024];
while(fis.read(bytes) != -1){
fos.write(bytes);
}
if(file.exists() && file.delete()) System.out.println("!");
else{
System.out.println("?");
}
}catch (Exception e){
System.out.println(e);
}finally {
try {
if(fis != null) fis.close();
if(fis != null) fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
查阅相关资料,发现delete需要先关闭流后,再进行删除(资源被占用,导致其他对象无法访问此资源)。文件剪切代码逻辑不够严禁。此处仅讨论delete一个文件问题。
FileOutputStream fos = null;
FileInputStream fis = null;
File file = null;
try{
file = new File("C:\\666.docx");
fis = new FileInputStream(file);
fos = new FileOutputStream("C:\\777.docx");
byte[] bytes = new byte[1024];
while(fis.read(bytes) != -1){
fos.write(bytes);
}
}catch (Exception e){
System.out.println(e);
}finally {
try {
if(fis != null) fis.close();
if(fis != null) fos.close();
} catch (IOException e) {
e.printStackTrace();
}
if(file.exists() && file.delete()) System.out.println("!");
else{
System.out.println("?");
}
}