Thursday, 22 June 2017

Remove File extension in Java ~ foundjava

An example logic on filtering the name of the file without extension in Java using String Handling and Java IO


Let's Filter


import java.io.*;
class RemoveExt
{
public static void main(String args[])
{

// Create a File object for C:\java
File f=new File("C:/java");

// Get all the files in a directory
File[] files=f.listFiles();

// Loop till end of all files
for(File t:files)
{
// Go inside only if file object t is not a directory
if(!t.isDirectory())
{
// Get the name of the file t
String name=t.getName();

// If name has an extension..
if(name.contains("."))
{

// Filter the name without extension
String extRemoved=name.substring(0,name.lastIndexOf('.'));

// Print the name with & without extension
System.out.println("Extension removed for "+name+" and it's now "+extRemoved);

}

}

}

}

}

For renaming the file:  You can use renameTo(File dest_file) method in the File class pointing the extRemoved [See above], this method should be called on the source file and the parameter is the complete path of the file that you were to rename.

No comments:

Post a Comment