java怎么判断一个文件是否存在

java怎么判断一个文件是否存在,第1张

用java.io.File类的public boolean exists()方法就能判断,如:

import java.io.*

public class Demo

{

public static void main(String[] args) throws Exception

{

//将p指定为文件的路径

String p="test.txt"

File f=new File(p)

if(f.isFile())

{

if(f.exists())

{

System.out.println("文件"+p+"存在。")

}

else

{

System.out.println("文件"+p+"不存在。")

}

}

else

{

System.out.println(p+"不是文件。")

}

}

}

1.File testFile = new File(testFilePath)

if(!testFile .exists()){

testFile.mkdirs()

System.out.println("测试文件夹不存在")

}

2.File testFile = new File(testFilePath)

if(!testFile .exists()){

testFile.createNewFile()

System.out.println("测试文件不存在")

}

java中File类自带一个检测方法exists可以判断文件或文件夹是否存在,一般与mkdirs方法(该方法相较于mkdir可以创建包括父级路径,推荐使用该方法)或者createNewFile方法合作使用。

1,如果路径不存在,就创建该路径

2,如果文件不存在,就新建该文件


欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/tougao/6046716.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-12
下一篇 2023-03-12

发表评论

登录后才能评论

评论列表(0条)

保存