【问题标题】:Detect that the file exists [duplicate]检测文件是否存在[重复]
【发布时间】:2012-10-25 07:06:36
【问题描述】:

请问如何检测文件是否存在,并且每次运行时不要创建一个新文件。

public static void main(String[] args) throws IOException, ClassNotFoundException {
    FileOutputStream fos = new FileOutputStream("file.tmp");
    ObjectOutputStream oos = new ObjectOutputStream(fos);

    oos.writeObject("12345");
    oos.writeObject("Today");

    oos.close();

} 

【问题讨论】:

  • 如果你看过File类的文档,你会发现:-File#exists方法。

标签: java file


【解决方案1】:

我认为这是你需要的:

public boolean settingsFileExits(final String fileName) {
    File f = new File(fileName);
    return f.exists();
}

【讨论】:

  • 为什么要使用三元运算符而不仅仅是“return f.exists();”?
  • L0L,你是对的! :D 我没看到...谢谢指正!
【解决方案2】:

不要使用FileOutputStream,而是使用File类然后做

如果 file.exists()

不要立即在堆栈溢出中询问,而是谷歌它。

【讨论】:

    【解决方案3】:

    使用File.exits():

    File f = new File("file.tmp");// this does not create a file
    
    if (f.exists()) {
        System.out.println("File existed");
    } else {
        System.out.println("File not found!");
    }
    

    那么你甚至可以使用构造函数FileOutputStream(File f, boolean append)

    【讨论】:

      【解决方案4】:

      使用文件类 API:

      File.exists

      【讨论】:

        【解决方案5】:

        怎么样

        File f = new File("file.tmp");
        if(f.exists()) {
         // do something
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-09
          • 2015-11-06
          • 2011-12-31
          • 2012-01-25
          相关资源
          最近更新 更多