我想保存文件中的内容,但首先我想搜索任何文件是否存在或不存在。但是,我写的代码,每次都返回true。如何检查文件是否退出?
String fileName=FNameTextField.getText();
File file=new File(fileName);
if(file.exists()&& !file.isDirectory()) {
// It returns true if File or directory does exist
System.out.println("the file or directory you are searching does exist : ");
}else{
// It returns true if File or directory not exists
System.out.println("the file or directory you are searching does not exist : ");
}
谢谢。
我强烈建议您考虑避免使用java.io.File来支持Java 7中引入的新API。特别是,[here](http://docs.oracle.com/javase /tutorial/essential/io/check.html)是解决此问题的相关Sun Java Trail教程。重要的方法是[Files.exists](http://goo.gl/SRTWb)。 – oldrinb 2012-08-04 05:34:24