Creating a file that does not exist........

Posted on 2000-01-30
Medium Priority
Last Modified: 2010-04-01
OK, here's a humdinger of a question.

I'm creating hashtables that are inputted into files of type .ser. Before putting a new entry into the hastable I read from a file that should contain the hashtable. However, if the file does not exist I want to be able to create the file to a specified name and then insert the hashtable entry. As of present it works if the file exists, otherwise it just bombs out and says FileNotFoundException. So, I reiterate, how can I create a file in my code?

Thank you
Question by:JavaJedi012400
  • 2

Accepted Solution

Jod earned 210 total points
ID: 2451022
You can create a File object to represent your file and then you can check whether it exists using the exists() method.

Then create it if neccessary using the createNewFile method.


public boolean createNewFile()
                      throws IOException

Automically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.


Expert Comment

ID: 2451061
In other words:

File f = new File("...myfile.txt");
if (!f.exists) f.createNewFile();

This will then create myfile.txt if it is not there.

Author Comment

ID: 2471802
Thank you. A good answer that didn't fully answer my question but pointed me in the right direction. Thanks again.

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
A discussion about automated testing of Web Applications utilizing Selenium, along with illustrated configuration steps for the Jenkins open source tool.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This video teaches viewers about errors in exception handling.
Suggested Courses

600 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question