-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
  • 48,723
  • 33
  • 63
  • 158
Mehdi
  • 2,060
  • 6
  • 35
  • 47
  • 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
  • 23,988
  • 12
  • 67
  • 136
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,835
  • 1
  • 18
  • 27
1

I think this is what you need:

public boolean settingsFileExits(final String fileName) {
    File f = new File(fileName);
    return f.exists();
}
assylias
  • 310,138
  • 72
  • 642
  • 762
KernelPanic
  • 2,406
  • 6
  • 42
  • 84
0

Use File class API:

File.exists

Azodious
  • 13,563
  • 1
  • 33
  • 68
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,026
  • 5
  • 39
  • 57