Mufasa King
Mufasa King

Reputation: 1

How to check if the string the user has entered contains a file extension

So in this program, a user is able to create/specify a directory and create a file, given that the file doesn't exist already. when the user is entering a file name, they are required to enter a file extension as well. The problem I am having is how to make the code look for a file extension at the end of the string the user inputs. I went as far as checking for a "." but I am stuck on a way that the program can see if the file has a .json or .txt or anything AFTER the "."

TL;DR How do I make the code check for a file extension at the end of a string a user has inputted (<- not a word)

Please note that the below code is not complete yet, the condition where I'm stuck at has a comment inside.

package filecreator.coolversion;

import java.io.File;
import java.io.IOException;
import java.util.*;

public class FileCreatorCoolversion {

public static Scanner sc = new Scanner(System.in);
public static boolean success = false;
public static String filename;
public static String filedir;
public static File file;
public static File dir;

public static void main(String[] args) throws IOException {

    System.out.println("********************************");
    System.out.println("* Welcome to File Creator 2.0! *");
    System.out.println("********************************");
    System.out.println(" ");

    while(!success) {

        System.out.println("Would you like to create a file? Y/N?");
        String usrans = sc.nextLine();

        if(usrans.equalsIgnoreCase("y")) {

            System.out.println("Proceeding with file creation...");
            break;

        } else if(usrans.equalsIgnoreCase("n")) {

            System.out.println("Exiting Program...");
            System.exit(0);

        } else if(!usrans.equalsIgnoreCase("y") || !usrans.equalsIgnoreCase("n")) {

            System.out.println("That is not a valid answer! Please try again!");
            System.out.println(" ");
        }
    }

    while(!success) {

        System.out.println(" ");
        System.out.println("Please enter a valid filename:");
        filename = sc.nextLine();

        if(filename.isEmpty()) {

            System.out.println("Please enter a file name!");
            break;

        } else if(filename.contains("/") || filename.contains(":") || 
                  filename.contains("*") || filename.contains("?") ||
                  filename.contains("<") || filename.contains(">") ||
                  filename.contains("|") || filename.contains("\"") ||
                  filename.contains("\\")) {

            System.out.println("Please do not include / \\ : * ? \" < > |");

        } else if(!filename.contains(".")) {

            System.out.println("Please add a apropriate file extensions");

        } else if (filename.) {

            //HERE IS WHERE IM STUCK

        } else {

            System.out.println(" ");
            System.out.println("File name \"" + filename + "\" chosen");
            break;
        }
    }

        System.out.println(" ");
        System.out.println("Where would you like to have your file saved?");
        System.out.println("Please enter a valid directory");

    while(!success) {

        filedir = sc.nextLine();

        if(!filename.contains(":")) {

            System.out.println(" ");
            System.out.println("Please enter a valid directory!");

        } else if(!filename.contains("\\")) {

            System.out.println(" ");
            System.out.println("Please enter a valid directory!");

        } else {

            System.out.println("File directory \"" + filedir + "\" chosen");
            break;
        }
    }

    System.out.println(" ");
    System.out.println("Creating file...");


}

}

Upvotes: 3

Views: 4575

Answers (3)

Gusti Arya
Gusti Arya

Reputation: 1301

if you want to get any extension after . you can use String split here some examples

String exts[] = filename.split("\\.");
int extIndex = exts.length;\\find array length incase user inputed more than one dot

System.out.println(exts[extIndex - 1]); \\ here you get the extension

Upvotes: 1

Falla Coulibaly
Falla Coulibaly

Reputation: 769

Find the file extension if any:

static String getExtension(String str){
    int begin = str.lastIndexOf(".");
    if(begin == -1)
        return null;
    String extension = str.substring(begin + 1);
    return extension;
}   

Check if the extension is valid:

static boolean isExtensionValid(String extension){
    String validExtensions [] = new String[]{
        "json", "txt"
    };
    for(String str : validExtensions )
        if(str.equals(extension))
            return true;

    return false;
}

Test the whole thing:

public static void main (String[] args){
    String val = "Kappa.txt";
    String extension = getExtension(val);

    if(extension != null){
        System.out.println(extension);
        System.out.println(isExtensionValid(extension));
    } else {
    //Handle no extension found here
    }
}

Upvotes: 1

Naman
Naman

Reputation: 31858

All you might want to do is check the lastIndex of the . which you checked in the previous condition and then see if there is any string after that or not:

String extension = filename.substring(filename.lastIndexOf(".") + 1);
//Checks if there is any extension after the last . in your input
if (!extension.isEmpty()) {
    System.out.print("This is the extension - " + extension);
}

Upvotes: 1

Related Questions