OCJP

Java Code to Change Extension of All the Files in a Folder

Using Java File Management you can change the name of file, get the list of all the files in folder and so many file related functionalities can be done. Here by we demonstrate an example to change the Extension of Files in a Folder. For the same we have used list() to get the files and renameTo() to rename the file.

import java.io.*;
class ChangeExtension{

public static void main(String []a)
{
	if(a.length<0)
	{
	System.out.println("\n[1]Folder Path [2] Current Extension [3] New Extension");
	return;
	}

	try{
	File fl= new File(a[0]);
	if(!fl.exists()){
	System.out.println("No Folder Founded");
	return;
	}

	String []files=fl.list();
	System.out.println("\n"+ files.length+" Files Founded");

	for(String f:files){
	File temp= new File(a[0]+"\\"+ f);
	if(temp.isFile()){
	String flnm= f.substring(0,f.lastIndexOf("."));
	String ext= f.substring(f.lastIndexOf(".")+1);
	System.out.println(ext+" = "+ a[1]);
	if(ext.equals(a[1]))
	flnm= flnm+"."+a[2];
	File newfile= new File(a[0]+"\\"+flnm);
	//System.out.println(flnm+" - "+ ext);
	temp.renameTo(newfile);
	System.out.println("Renamed to "+ flnm);
	}
	}
	}catch(Exception e)
	{
	e.printStackTrace();
	}
} 
}
javac ChangeExtension.java

java ChangeExtension c:\\myfolder_path old_extension new_extension

eg.
java ChangeExtension c:\\myweb\\files html php

Above command will change all html files to php in folder files in myweb.

Leave a Reply

Your email address will not be published. Required fields are marked *


× How can I help you?