MarkLoveExEx
asked on
Java rename file(s) question - regular expressions
Using Java, I need to rename a bunch of files located in a directory. The files are named like this (where the numbers are different in each file):
serfc_xmrg0127201611z
I need to rename them, getting rid of the beginning "serfc_" So, change it to:
xmrg0127201611z
I've "grabbed" the files in an array with the following:
// rename files (get rid of serfc_ in the filename)
File dir300 = new File("/awips/hydroapps/lx/ rfc/nwsrfs /ofs/files /oper/grid db");
File[] toBeRenamed = dir300.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return (pathname.getName().starts With("serf c"));
}
});
And I have the following:
for (File f : toBeRenamed) {
try {
String name = f.getName().replaceAll("(? i)\\.gz$", ""); //I know this is wrong
//what do I put here?
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedOperationExcep tion e) {
e.printStackTrace();
}
}
Please help me fill this in. Thanks. Mark
serfc_xmrg0127201611z
I need to rename them, getting rid of the beginning "serfc_" So, change it to:
xmrg0127201611z
I've "grabbed" the files in an array with the following:
// rename files (get rid of serfc_ in the filename)
File dir300 = new File("/awips/hydroapps/lx/
File[] toBeRenamed = dir300.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return (pathname.getName().starts
}
});
And I have the following:
for (File f : toBeRenamed) {
try {
String name = f.getName().replaceAll("(?
//what do I put here?
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedOperationExcep
e.printStackTrace();
}
}
Please help me fill this in. Thanks. Mark
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks.
You're welcome!
ASKER
for (File f : toBeRenamed) {
try {
String name = f.getName().replaceAll("se
InputStream in = new FileInputStream(f);
File target = new File(dir300, name);
Files.copy(in, target.toPath(), StandardCopyOption.REPLACE
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedOperationExcep
e.printStackTrace();
}
}