How to Trim a File Extension from a String in Java

Remove the extension of a file

Something like

if (name.indexOf(".") > 0)
name = name.substring(0, name.lastIndexOf("."));

The index check avoids turning hidden files like ".profile" into "", and the lastIndexOf() takes care of names like cute.kitty.jpg.

How to trim a file extension from a String in JavaScript?

If you know the length of the extension, you can use x.slice(0, -4) (where 4 is the three characters of the extension and the dot).

If you don't know the length @John Hartsock regex would be the right approach.

If you'd rather not use regular expressions, you can try this (less performant):

filename.split('.').slice(0, -1).join('.')

Note that it will fail on files without extension.

Remove filename extension in Java

I'm going to have a stab at this that uses the two-arg version of lastIndexOf in order to remove some special-case checking code, and hopefully make the intention more readable. Credit goes to Justin 'jinguy' Nelson for providing the basis of this method:

public static String removeExtention(String filePath) {
// These first few lines the same as Justin's
File f = new File(filePath);

// if it's a directory, don't remove the extention
if (f.isDirectory()) return filePath;

String name = f.getName();

// Now we know it's a file - don't need to do any special hidden
// checking or contains() checking because of:
final int lastPeriodPos = name.lastIndexOf('.');
if (lastPeriodPos <= 0)
{
// No period after first character - return name as it was passed in
return filePath;
}
else
{
// Remove the last period and everything after it
File renamed = new File(f.getParent(), name.substring(0, lastPeriodPos));
return renamed.getPath();
}
}

To me this is clearer than special-casing hidden files and files that don't contain a dot. It also reads clearer to what I understand your specification to be; something like "remove the last dot and everything following it, assuming it exists and is not the first character of the filename".

Note that this example also implies Strings as inputs and outputs. Since most of the abstraction requires File objects, it would be marginally clearer if those were the inputs and outputs as well.

Remove extension from file name with help of stream

You are wasting resources by converting the path to a string multiple times. When the intended end result is a string anyway, you can map to a string right as the first step, so you don’t need to repeat it.

return Files.walk(Paths.get(qPath))
.map(p -> p.getFileName().toString())
.filter(name -> name.endsWith(".txt"))
.map(name -> name.substring(0, name.length()-".txt".length()))
.findFirst()
.get();

Note that it doesn’t matter whether you place the last .map(…) step before the findFirst(), i.e. apply it to the Stream, or after it, applying it to the Optional. Due to the lazy nature of the Stream, it will still only applied to the first matching element here. But I prefer keeping the .endsWith(".txt") test and the subsequent .substring(0, name.length()-".txt".length()) as close together as possible, to make the relationship between these two steps more obvious.

Remove file name extension

Use this:

String test =  "myfile.jpg.des";
test = test.substring(0, test.lastIndexOf("."));

Java - How to get the name of a file from the absolute path and remove its file extension?

If you're working strictly with file paths, try this

String path = "C:\\Users\\Ewen\\AppData\\Roaming\\MyProgram\\Test.txt";
File f = new File(path);
System.out.println(f.getName()); // Prints "Test.txt"

Thanks but I also want to remove the .txt

OK then, try this

String fName = f.getName();
System.out.println(fName.substring(0, fName.lastIndexOf('.')));

Please see this for more information.

How do I get the file extension of a file in Java?

In this case, use FilenameUtils.getExtension from Apache Commons IO

Here is an example of how to use it (you may specify either full path or just file name):

import org.apache.commons.io.FilenameUtils;

// ...

String ext1 = FilenameUtils.getExtension("/path/to/file/foo.txt"); // returns "txt"
String ext2 = FilenameUtils.getExtension("bar.exe"); // returns "exe"

Maven dependency:

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>

Gradle Groovy DSL

implementation 'commons-io:commons-io:2.6'

Gradle Kotlin DSL

implementation("commons-io:commons-io:2.6")

Others https://search.maven.org/artifact/commons-io/commons-io/2.6/jar

How to trim only the file name from a path which is having filename with extension using java script?

Firstly i believe that you have to escape your backslash so the correct way to extract your filename would be var documentName = $('#documentFile').val().split('\\').pop(). After this you can just chain a .split() to your code and it should work. you could try var documentName = $('#documentFile').val().split('\\').pop().split(".")[0]



Related Topics



Leave a reply



Submit