示例一:
package com.yiibai;import java.io.file;public class fileexistence { public static void main(string[] args) { file file = new file("f:/worksp/javaexamples/java_files/myfile.txt"); system.out.println(file.exists()); }}
执行上述示例代码,将产生以下结果 -
trueshell
免费相关视频教程:java在线教程
示例二:
package com.yiibai;import java.io.file;import java.io.filenotfoundexception;import java.io.ioexception;import java.io.printwriter;import java.nio.file.filealreadyexistsexception;import java.nio.file.files;import java.nio.file.path;import java.nio.file.paths;public class fileexistence2 { public static void main(string[] args) throws ioexception { file f = new file(system.getproperty("user.dir")+"/folder/file.txt"); system.out.println(f.exists()); if(!f.getparentfile().exists()){ f.getparentfile().mkdirs(); } if(!f.exists()){ try { f.createnewfile(); } catch (exception e) { e.printstacktrace(); } } try { file dir = new file(f.getparentfile(), f.getname()); printwriter pwriter = new printwriter(dir); pwriter.print("writing anything..."); pwriter.close(); } catch (filenotfoundexception e) { e.printstacktrace(); } }}
执行上述示例代码,将产生以下结果:
falseshell
再运行一次则返回来的结果为:
true
想了解更多java相关知识可以访问:java入门程序
以上就是java中如何判断file是否存在的详细内容。