Jump to content

Renaming files in a directory

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
Guest_anand.sundaramurthy_*

Guest_anand.sundaramurthy_*
  • Guests
Hi All,
Am trying to rename all the files in a given directory,for ex if theres a file called hello.xls,hello1.xls then after the execution of the program it must become hello_Bs.xls,hello1_Bs.xls
I have written a simple code for this but am getting null pointer exception.
can anybody pls temme wats worng with the code.

import java.io.*;
import java.lang.*;
import java.util.*;

public class Ls {
	public static void main(String args[]) 
	{
		String[] dir = new java.io.File("c:\\Documents and Settings\\Admin\\Desktop\\New Folder").list();
		java.util.Arrays.sort(dir); 
		File f[] = new File("c:\\Documents and Settings\\Admin\\Desktop\\New Folder)").listFiles();
		int len1 = dir.length;
		for (int i=0;i<len1; i++)
		{
			System.out.println(dir[i]);
			String name = f[i].getName();
			System.out.println(name);
			int j=name.indexOf('.');
			System.out.println(j);
			String newname = name.substring(0,j-1) + "_BS" + name.substring(j+1,name.length());	
			System.out.println(newname);
			File newFileName=new File(f[i].getParentFile(), newname);
			System.out.println("newFileName="+newFileName);
			f[i].renameTo(newFileName);   
		}
	}	
}


#2
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
I don't have time to dig into it right now, but this is your problem:

f[i].getName()


#3
oubless

oubless

    Newbie

  • Members
  • PipPip
  • 22 posts
The problem is here

String newname = name.substring(0,j-1) + "_BS" + name.substring(j+1,name.length());	

substring( a, b ) means including a excluding b

Fixed:


import java.io.File;


public class Ls {

	public static void main(String args[]) 

	{

		String[] dir = new java.io.File("test").list();

		java.util.Arrays.sort(dir); 

		File f[] = new File("test").listFiles();

		int len1 = dir.length;

		for (int i=0;i<len1; i++)

		{

			System.out.println(dir[i]);

			String name = f[i].getName();

			System.out.println(name);

			int j=name.indexOf('.');

			System.out.println(j);

			String newname = name.substring(0,j) + "_BS" + name.substring(j,name.length());	

			System.out.println(newname);

			File newFileName=new File(f[i].getParentFile(), newname);

			System.out.println("newFileName="+newFileName);

			f[i].renameTo(newFileName);   

		}

	}	

}



#4
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
Ohh, how simple. I should of seen that!

#5
Patrick

Patrick

    Programmer

  • Members
  • PipPipPipPip
  • 101 posts
Hi,

I tried this program but I am getting some problem in calling the "i" string. Could you please specify what "i" string is doing.

Thanks a lot.