public boolean deleteFile(String sPath) {
boolean flag = false;
File file = new File(sPath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
System.out.println("delete file.");
flag = true;
return flag;
}
单独测试删除代码没有问题。
后来在读文件的方法中调用删除方法,在读取完毕后删除。
public void readFile(String filename)
FileReader reader = null;
reader = new FileReader(filename);// 读取url文件
catch (FileNotFoundException e)
// TODO Auto-generated catch block
e.printStackTrace();
String name = filename.split("\\\\")[filename.split("\\\\").length-1];
System.out.println("filename is "+ filename);
BufferedReader br = new BufferedReader(reader);
String s1 = null;
String temStr = "";
String content = "";
int breakCount = 0;
while ((s1 = br.readLine()) != null)
breakCount++;
if(s1.contains("------------------------"))
if(breakCount == 2 && s1.contains("docid"))
break;
if(breakCount != 2)
System.out.println(breakCount);
boolean flag = deleteFile(filename);
System.out.println(flag);
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
br.close();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
reader.close();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
}
这样写的时候遇到了问题,delete方法返回了true值,但是文件并没有被删除
检查之后发现是因为文件的读取流未关闭,造成文件无法删除。
但是为什么会返回true还没有确定,估计是个小bug吧
把代码修改一下
public void readFile(String filename)
FileReader reader = null;
reader = new FileReader(filename);// 读取url文件
catch (FileNotFoundException e)
// TODO Auto-generated catch block
e.printStackTrace();
String name = filename.split("\\\\")[filename.split("\\\\").length-1];
System.out.println("filename is "+ filename);
BufferedReader br = new BufferedReader(reader);
String s1 = null;
String temStr = "";
String content = "";
int breakCount = 0;
while ((s1 = br.readLine()) != null)
breakCount++;
if(s1.contains("------------------------"))
if(breakCount == 2 && s1.contains("docid"))
break;
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
br.close();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
reader.close();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
if(breakCount != 2)
System.out.println(breakCount);
boolean flag = deleteFile(filename);
System.out.println(flag);
}
把删除放在流关闭之后,这样就没有问题了