【问题标题】:How to check the file string path is valid in java如何检查文件字符串路径在java中是否有效
【发布时间】:2014-12-05 11:00:11
【问题描述】:

我是java的初学者,我想检查用户为文件提供的字符串路径是否有效,例如路径是否存在,如果包含不为空并且文件不为空等等。如何我可以这样做吗?

private static final String FILE_PATH = "com.var.file.path";
String file_path = System.getProperty(FILE_PATH, DEFAULT_FILE_PATH);

【问题讨论】:

  • ...new File(file_path).exists()?!
  • 您使用的是哪个版本的 Java?如果 7+ 你也可以使用Files.exists(Paths.get(file_path))
  • 当文件不存在时,如何通过记录器记录错误消息?文件不存在后代码卡住了
  • 你在使用java.util.logging吗?
  • 是的,我使用它,我需要关闭文件,但不知道在 try and catch 中在哪里执行此操作

标签: java


【解决方案1】:

File 类中内置了一个布尔值,可以为您检查它。

做:

if(new File(file_path).exists())
{
    //Do Stuff
}else{
    System.err.println("Error: " + file_path + " does not exist.");
    //Or whatever other output stream you want to use
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-23
    • 2011-03-09
    • 2018-05-23
    • 2022-12-15
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 2014-09-04
    相关资源
    最近更新 更多