[英]Delete Temp File in Java
Am having the below code , creating a Temp file and read that and deleting the file. 具有以下代码,创建一个Temp文件并读取该文件并删除该文件。 But after deletion also file available to read .Please help to find wrong with my code....
但是删除后还可以读取文件。请帮助查找我的代码错误...。
public static void main(String args[]) throws Exception
{
Calendar mSec = Calendar.getInstance();
String fileName="hubname_"+"msgname_"+mSec.getTimeInMillis();
String str ="Hello How are you doing .......";
System.out.println("fileName :"+fileName);
File f = File.createTempFile(fileName, ".xml");
FileWriter fw = new FileWriter(f);
fw.write(str);
fw.flush();
fw.close();
printFileContent(f);
f.delete();
printFileContent(f);
}
public static void printFileContent(File f)throws Exception
{
BufferedReader reader = new BufferedReader( new FileReader(f));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while( ( line = reader.readLine() ) != null ) {
stringBuilder.append( line );
stringBuilder.append( ls );
}
System.out.println("stringBuilder.toString() :"+stringBuilder.toString());
}
Output : 输出:
fileName :hubname_msgname_1358655424194
stringBuilder.toString() :Hello How are you doing .......
stringBuilder.toString() :Hello How are you doing .......
You should close reader in printFileContent. 您应该在printFileContent中关闭阅读器。 File.delete cannot delete an opened file (at least on Windows, see Keith Randall's comment below) in which case it returns false.
File.delete无法删除打开的文件(至少在Windows上,请参见下面的Keith Randall的注释),在这种情况下它将返回false。 You could check if delete was successful
您可以检查删除是否成功
if (!f.delete()) {
throw new IOException("Cannot delete " + f);
}
The following comment was added to File.delete API in Java 7 以下注释已添加到Java 7中的File.delete API中
Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.
public static void printFileContent(File f)throws Exception
{
BufferedReader reader = new BufferedReader( new FileReader(f));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while( ( line = reader.readLine() ) != null ) {
stringBuilder.append( line );
stringBuilder.append( ls );
}
System.out.println("stringBuilder.toString() :"+stringBuilder.toString());
if(reader != null){
reader.close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.