newbie question: loop through directory and change file names

L

lawrence

This is my first attempt to write a java program. I want to write a
litttle macro that will show up as an icon. When I put in a directory
and double click it, I want it to launch and loop through every file
in the directory and change the names of the files. Specifically, I
want it to find open ' ' white spaces and change them to an
underscore: _

I'm doing this because I've several hundred images I'd like to upload
to the web, but they are on a Windows machine and they have spaces in
their name.

Looking around online I found examples of how to open a directory, get
a list of the files, and replace the white spaces with underscores,
but I don't know how to actually replace the old name with the new
name.

Any advice?




/*
* changeFileNames.java
*
* Created on November 20, 2004
*/

/**
*
* @author Lawrence
*/
public class changeFileNames {


public changeFileNames {

}



/**
* @param args the command line arguments
*/
public static void main(String args[]) {
File dir = new File("directoryName");

String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
for (int i=0; i<children.length; i++) {
// Get filename of file or directory
String filename = children;
// Convert to lower case
String newFileName = filename.toLowerCase();
newFinalName = newFileName.replace(' ', '_');
}
}

}

}
 
N

Neil Campbell

lawrence said:
This is my first attempt to write a java program. I want to write a
litttle macro that will show up as an icon. When I put in a directory
and double click it, I want it to launch and loop through every file
in the directory and change the names of the files. Specifically, I
want it to find open ' ' white spaces and change them to an
underscore: _

I'm doing this because I've several hundred images I'd like to upload
to the web, but they are on a Windows machine and they have spaces in
their name.

Looking around online I found examples of how to open a directory, get
a list of the files, and replace the white spaces with underscores,
but I don't know how to actually replace the old name with the new
name.

Any advice?

You probably want to look at the File.renameTo(File) function. You can
create a File object for the file you want to rename, create a new file
object with the new name, and call renameTo to rename the file.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,527
Members
44,998
Latest member
MarissaEub

Latest Threads

Top