0

So i'm trying to take user input that has a extension like .txt or .html but I'm not sure if you can do String slicing in Java like you can in Python. Could I please get some help? I'm trying to understand the concept and not just get an easy answer.

    import java.util.Scanner;
public class FileReader {


  public static void main(String[] args) { 
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Please enter a file name and its extension!");
    String fileName = keyboard.next();
    System.out.println(fileName);
    String[] parts = fileName.split("");
    String ext = parts[0];

  }

  /* ADD YOUR CODE HERE */

}
Ethan Collins
  • 45
  • 1
  • 6
  • Dupe: [How do I get the file extension of a file in Java?](http://stackoverflow.com/q/3571223) – Tom Sep 14 '16 at 01:35

2 Answers2

2

Try to split on the .:

String[] parts = fileName.split("\\.");
String ext = parts[1];  // the extension will be the second part

But it might better to test if there are two parts though using:

if (parts.length > 1) {
    ext = parts[1];
}
else {
    ext = "No extension";
}

If you like to support dots in the regular filename, then use this approach:

if (parts.length > 1) {
    ext = parts[parts.length - 1];
}
else {
    ext = "No extension";
}
Tom
  • 16,842
  • 17
  • 45
  • 54
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
1

You could also use substring along with lastIndexOf:

String fileName = keyboard.next();
int lastDotIndex = fileName.lastIndexOf(".");
String ext = "":
if (lastDotIndex > 0) {
    ext = filename.substring(fileName.lastIndexOf(".") + 1);
}

If no extension be present, then this code snippet will return empty string. Otherwise, it will return what it perceives to be the extension.

Here is another clever method using regular expressions:

String filename = "some.file.name.txt";
String ext = filename.indexOf(".") > 0 ? filename.replaceAll("^.*\\.(\\w+)$", "$1") : "";

The .* in the regex will greedily consume until hitting the final extension, if it be present, and it will retain only this final extension. You can explore this regex here:

Regex101

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Please leave some feedback. We use this method in production. – Tim Biegeleisen Sep 14 '16 at 01:31
  • I'm not the downvoter, but you might want to use existing libs like [Guava](https://google.github.io/guava/releases/19.0/api/docs/com/google/common/io/Files.html#getFileExtension(java.lang.String)) or [Apache Commons IO](http://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FilenameUtils.html#getExtension%28java.lang.String%29) to avoid re-inventing the wheel. – Tom Sep 14 '16 at 01:35