Sunday 12 January 2020

Java: Get file name by removing extension


Below snippet return the file name by removing extension.
public static String getFileName(String file) {
 if (file == null || file.isEmpty()) {
  return file;
 }

 int lastIndex = file.lastIndexOf(".");

 if (lastIndex == -1) {
  return file;
 }

 return file.substring(0, lastIndex);
}


App.java
package com.sample.app;

import java.io.IOException;

public class App {

 public static String getFileName(String file) {
  if (file == null || file.isEmpty()) {
   return file;
  }

  int lastIndex = file.lastIndexOf(".");

  if (lastIndex == -1) {
   return file;
  }

  return file.substring(0, lastIndex);
 }

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

  String file1 = "abc.txt";
  String file2 = "abc";
  String file3 = "abc.tt.bkp.txt";

  String fileName1 = getFileName(file1);
  String fileName2 = getFileName(file2);
  String fileName3 = getFileName(file3);

  System.out.println("For file '" + file1 + "' name is '" + fileName1 + "'");
  System.out.println("For file '" + file2 + "' name is '" + fileName2 + "'");
  System.out.println("For file '" + file3 + "' name is '" + fileName3 + "'");

 }

}

Output
For file 'abc.txt'  name is 'abc'
For file 'abc'  name is 'abc'
For file 'abc.tt.bkp.txt'  name is 'abc.tt.bkp'


You may like

No comments:

Post a Comment