Creating a File


File f = new File("myfile.txt"); boolean result = f.createNewFile();



This phrase uses the createNewFile() method to create a new file with the filename specified when constructing the File objectin this case, myfile.txt. The createNewFile() method will return a boolean value of true if the file was successfully created and false if the specified filename already exists.

Another method is available in the File class for creating a temporary file: It's called createTempFile(). This is a static method on the File class. Here, we show how to use this method to create a temporary file:

File tmp =    File.createTempFile("temp", "txt", "/temp");


The parameters that we pass to the createTempFile() method are the temp file's prefix, suffix, and the temp directory. Another version of this method is available that takes just two parameters and uses the default temp directory. For either form of the createTempFile() method to work, the specified file must not already exist.

If you are using temporary files, you'll also be interested in the deleteOnExit() method of the File class. You should call the deleteOnExit() method on a File object that represents a temporary file. Calling the deleteOnExit() method requests that the file be deleted automatically when the Java virtual machine terminates.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net