Create new empty file

  1. /*
  2.   Create new empty file
  3.   This Java example shows how to create new empty file at specified path using
  4.   createNewFile method of Java File class.
  5. */
  6.  
  7. import java.io.*;
  8.  
  9. public class CreateNewEmptyFile {
  10.  
  11. public static void main(String[] args) {
  12.  
  13. //create File object
  14. File file = new File("C://demo.txt");
  15.  
  16. /*
  17.   * To actually create a file specified by a pathname, use
  18.   * boolean createNewFile() method of Java File class.
  19.   *
  20.   * This method creates a new empty file specified if the file with same
  21.   * name does not exists.
  22.   *
  23.   * This method returns true if the file with the same name did not exist and
  24.   * it was created successfully, false otherwise.
  25.   */
  26.  
  27. boolean blnCreated = false;
  28. try
  29. {
  30. blnCreated = file.createNewFile();
  31. }
  32. catch(IOException ioe)
  33. {
  34. System.out.println("Error while creating a new empty file :" + ioe);
  35. }
  36.  
  37. System.out.println("Was file " + file.getPath() + " created ? : " + blnCreated);
  38.  
  39. /*
  40.   * If you run the same program 2 times, first time it should return true.
  41.   * But when we run it second time, it returns false because file was already
  42.   * exist.
  43.   */
  44. }
  45. }
  46.  
  47. /*
  48. Output would be
  49. Was file C:\demo.txt created ? : true
  50. */

Post new comment

To combat spam, please enter the code in the image.


Suggested Reading

Oracle Magazine
Contains technology strategy articles, sample code, tips, Oracle and partner news, how to articles for developers and DBAs, and more.
Cost: FREE

View/Subscribe
NASA Tech Briefs
Features exclusive reports of innovations developed by NASA and its industry partners/contractors that can be applied to develop new/improved products and solve engineering or manufacturing problems.
Cost: FREE

View/Subscribe
FierceBiotech IT
Is a free, easy to read weekly email service that brings must read biotech IT news to senior biotech, pharma, and IT executives.
Cost: FREE

View/Subscribe
Simply SQL
Simply SQL is a practical step-by-step guide to writing SQL.
Cost: FREE

View/Subscribe
Simply JavaScript
Packed with full-color examples, Simply JavaScript is all you need to start programming in JavaScript the right way.
Cost: FREE

View/Subscribe
PCMag.com's What's New Now
Lance Ulanoff, Editor in Chief of the PC Magazine Network, brings you this twice-weekly roundup of the latest top tech stories, the best new product reviews, plus special offers from Ziff Davis and its partners.
Cost: FREE

View/Subscribe

Could not find what you are looking for? Search Java Examples




Feel Tired? Read Jokes & Inspirational Stories, Play Games!