Skip to main content
gamedev.net
🔒 Locked

Java - Creating files

Started by Mastermind25200 1 reply 550+ views
Original Post
Mastermind25200
Mastermind25200
I have a small problem. I was messing around in Java with the file IO for a game I'm going to make. Well, I want to be able to create a file if it doesn't exist, however if it DOES exist, then do absolutely nothing. It's probably real simple, but I don't know how to do this in Java. Any help? Thanks.
stormrunner
stormrunner
Yeah, it's pretty simple. Just use the java.io.File class, and check to see if it exists e.g. :
import java.io.*;// ...// inside some function somewhere// ...File file = new File("myFile.txt");if(file.exists()){   System.out.println("The file [" + filename + "] exists");   // since it exists, just return, continue or break   return;}else // create the file using a FileOutputStream or something{   // here, we use a FileOutputStream,   // but you should use a BufferedOutputStream   // in most situations for performance reasons   // if you're going to keep the stream open and use it   try {      FileOutputStream filestream = new FileOutputStream(file);   // the file has been created   // close it ... or do something else   }   catch(IOException ex) {      // save the day   }}

You should (might) probably need to wrap that in a try/catch block, but that should do the trick. For directories you can do something like the following
File f = new File("omgDir");f.mkDir();

to create a directory, though be careful - java.io functions aren't known for their reliability.

<edit :: I just realized you could substitute the FileOutputStream code with a simple file.createNewFile() (it's late). I just assumed you would want to replace the data but that should be a little easier.
stormrunner
Spudder
Spudder
Your going to need a try/catch block for FileNotFoundException, the compiler won't let you get away without one since it's a checked exception.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.