Tuesday, November 08, 2011

Create file and overwrite if it exists

The following code 'll delete the file 'myfile.html' if exists and 'll create a new file 'myfile.html'
  1. File f = new File("myfile.html");
  2. if(f.exists()){
  3. f.delete();
  4. f.createNewFile();
  5. }

Create file if it does not exist

The following code 'll create a file 'examplefile.txt',if doesn't exist
  1. try {
  2.  File file = new File("examplefile.txt");
  3.  // Create file if it does not exist
  4.  boolean success = file.createNewFile();
  5.  if (success) {
  6.  // File did not exist and was created
  7.  } else {
  8.  // File already exists
  9.  }
  10. } catch (IOException e) {
  11. e.printStackTrace();
  12. }