I think Due to recursion it is taking time but in which part of the code it is consuming more time and where to optimize the code.
Code:
package scanmove;
import java.io.*;
import java.util.*;
class scanmove
{
static String destination="F:\\destination\\";
static Vector <String> vs=new Vector();
public static void main(String args[])
{
String s[]= {"","D:\\Files\\"};
recurse(s,s[0]);
separate();
}
public static void recurse(String s[],String base)
{String url;
try
{
for(int i=0;i<s.length;i++)
{
url=base+s[i];
File f=new File(url);
if(f.exists())
{
vs.addElement(url);
if(f.isDirectory())
{
recurse(f.list(),url+"\\");
}
}
}
}
catch(Exception e)
{
System.err.println(e.getMessage());
}
}
public static void separate()
{
String s="";
try
{
File f,f1;
for(int i=0;i<vs.size();i++)
{
f=new File(vs.elementAt(i));
if(f.isDirectory())
{
vs.remove(i);
continue;
}
if(f.isFile())
{
int x;
if((x=vs.elementAt(i).lastIndexOf("."))!=-1)
s=vs.elementAt(i).substring(x,vs.elementAt(i).length()-1);
else
s=".";
f1=new File(destination+s);
if(!f1.mkdir())
{
System.out.println("unable to make directory "+s);
}
for(int j=0;j<vs.size();j++)
{
f=new File(vs.elementAt(j));
if(f.isDirectory())
{
vs.remove(j);
continue;
}
if((x==-1&&vs.elementAt(j).lastIndexOf(".")==-1)||(s.equalsIgnoreCase(vs.elementAt(j).substring(vs.elementAt(j).lastIndexOf("."),vs.elementAt(j).length()-1))))
{
move(vs.elementAt(j),destination+s);
vs.remove(j);
}
}
}
}
if(vs.size()!=0)
{
separate();
}
}
catch(Exception e)
{
System.err.println(e.getMessage());
}
}
public static void move(String file,String destination)
{
System.out.println(file+"\nmoved to\n"+destination);
try
{
File f=new File(file);
File f1=new File(destination+"\\"+f.getName());
FileInputStream fr=new FileInputStream(f);
FileOutputStream fw=new FileOutputStream(f1);
int i;
while((i=fr.read())!=-1)
{
fw.write(i);
}
if(!f.delete())
{
System.out.println("unabale to delete");
}
}
catch(Exception e)
{
System.err.println(e.getMessage());
}
}
}
Comment