-2

Please how to detect that the file exists and don't create a new one each time I run it.

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();

} 
Roman C
  • 49,761
  • 33
  • 66
  • 176
Mehdi
  • 2,160
  • 6
  • 36
  • 53
  • 2
    Had you gone through the documentation of `File` class, you would have found : - [`File#exists`](http://docs.oracle.com/javase/7/docs/api/java/io/File.html#exists()) method. – Rohit Jain Nov 05 '12 at 12:37

5 Answers5

2

How about

File f = new File("file.tmp");
if(f.exists()) {
 // do something
}
Aleksandr M
  • 24,264
  • 12
  • 69
  • 143
1

Use 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!");
}

Then you can even use the constructor FileOutputStream(File f, boolean append)

thedayofcondor
  • 3,860
  • 1
  • 19
  • 28
1

I think this is what you need:

public boolean settingsFileExits(final String fileName) {
    File f = new File(fileName);
    return f.exists();
}
assylias
  • 321,522
  • 82
  • 660
  • 783
KernelPanic
  • 2,328
  • 7
  • 47
  • 90
0

Use File class API:

File.exists

Azodious
  • 13,752
  • 1
  • 36
  • 71
0

Instead of using FileOutputStream use File class then do

if file.exists()

And

Instead of asking immediately in stack over flow, google it.

vels4j
  • 11,208
  • 5
  • 38
  • 63