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+"不是文件。")

}

}

}

public static void main(String[] args) {

if(new File("c:/test.txt").exists())

System.out.println("存在")

}

public static File checkExist(String filepath) throws Exception{

File file=new File(filepath)

if (file.exists()) {//判断文件目录的存在

System.out.println("文件夹存在!")

if(file.isDirectory()){//判断文件的存在性

System.out.println("文件存在!")

}else{

file.createNewFile()//创建文件

System.out.println("文件不存在,创建文件成功!" )

}

}else {

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

File file2=new File(file.getParent())

file2.mkdirs()

System.out.println("创建文件夹成功!")

if(file.isDirectory()){

System.out.println("文件存在!")

}else{

file.createNewFile()//创建文件

System.out.println("文件不存在,创建文件成功!" )

}

}

return file

}


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

原文地址:https://54852.com/tougao/11783706.html

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

发表评论

登录后才能评论

评论列表(0条)

    保存