Jarrod Nobel Jarrod Nobel - 1 year ago 85
Java Question

Default Filename for no answer

So i have a program that creates a new file but need it to have a default file name if the user was to not enter anything, and was wondering if anyone could help with it.

So far i have the program asking the user for the file name but not sure what to do to set the default to for say "output.txt".

Here is a snip-it of my code:

//Creates a Scanner Object for keyboard input.
Scanner keyboard = new Scanner(System.in);

//Get the filename.
System.out.print("Enter a filename: ");
filename = keyboard.nextLine();

Answer Source

You have to test if the string is empty, which can be done with String#isEmpty in conjuction with String#trim, from the documentation:


public boolean isEmpty()

Returns true if, and only if, length() is 0.

That means, once we trim to remove whitespace, we can test if length is 0. Thus, any inputs that consist of just spaces will not be used as filenames, and will default, else it will used the given. You can apply this like so:

File file = new File(filename.trim().isEmpty() ? "output.txt" : filename);

try {       
} catch(IOException ex) {
    //file was not created successfully

This will create a new File object, which will have a filename based on if the user inputted anything (whitespace excluded). file.createNewFile() will just create the file if it does not exist.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download