-1

I have a file name reader from a folder.file`s names taken into a string array.what i want is when i executed this code segment i want the file name without its extension. But still extensions get printed out.

import java.io.File;
public class Main {

    public static void main(String[] args) {
        File file=new File("D:\\C_App\\PDF");
        String[] files = file.list();
        for(String string : files) {
            string.substring(0, string.length());
            System.out.println(string);
        }
    }
}

Can anyone help me to solve this? Thanks.

D.Anush
  • 33
  • 6
  • 2
    Just so you ALL know...A file name doesn't necessarily need to contain a file name extension. NONE of your answers takes this into account. @D.Anush - Check out the thread in [this SO Post](https://stackoverflow.com/questions/924394/how-to-get-the-filename-without-the-extension-in-java). – DevilsHnd - 退職した Aug 22 '18 at 05:23
  • 1
    Strings are immutable in java. The `substring` method returns a **new** string that you need to assign to a variable. – Mark Rotteveel Aug 22 '18 at 08:45

3 Answers3

1

Take substring of string from the last index of .

import java.io.File;
public class Main {

    public static void main(String[] args) {
        File file=new File("D:\\C_App\\PDF");
        String[] files = file.list();
        for(String string : files) {
             if(new File(string).isFile){ 
               if (string.lastIndexOf(".") > 0) {
                  System.out.println(string.substring(0, a.lastIndexOf('.'));
               }
            else {
               System.out.println(string);
            }
           }
        }
    }
}
Kaustubh Khare
  • 3,280
  • 2
  • 32
  • 48
0

using regex by matching the last dot ( . ) and split,

the regex (\\.)(?!.*\\.) matches the last dot.

import java.io.File;
public class Main {
public static void main(String[] args) {
    File file=new File("D:\\C_App\\PDF");
    String[] files = file.list();
    for(String string : files) {
      if (!string.isEmpty()) {
        System.out.println(string.split("(\\.)(?!.*\\.)")[0]);
      }
    }
}
The Scientific Method
  • 2,374
  • 2
  • 14
  • 25
0

Here is the Solution:

public static void main(String[] args) {
    File file = new File("D:\\SunilKanjar");
    String[] files = file.list();
    for (String string : files) {
        if (string.lastIndexOf(".") > 0) {
            System.out.println(string.substring(0, string.lastIndexOf(".")));
        }
    }
}

To get file name without extension first of all we need to find is there any extension or not and then need to remove extension only and for that find . at from the last.

It is not accurate to assume that file name not contain more then one . sign.

Sunil Kanzar
  • 1,244
  • 1
  • 9
  • 21