Link to home
Start Free TrialLog in
Avatar of MarkLoveExEx
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/griddb");
                  File[] toBeRenamed = dir300.listFiles(new FileFilter() {
                        public boolean accept(File pathname) {
                              return (pathname.getName().startsWith("serfc"));
                        }
                  });

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 (UnsupportedOperationException e) {
                              e.printStackTrace();
                        }
                  }

Please help me fill this in. Thanks.  Mark
Avatar of MarkLoveExEx
MarkLoveExEx

ASKER

I figured it out:
                  for (File f : toBeRenamed) {
                        try {
                              String name = f.getName().replaceAll("serfc_","");
                              InputStream in = new FileInputStream(f);
                              File target = new File(dir300, name);
                              Files.copy(in, target.toPath(), StandardCopyOption.REPLACE_EXISTING);

                        } catch (FileNotFoundException e) {
                              e.printStackTrace();
                        } catch (IOException e) {
                              e.printStackTrace();
                        } catch (UnsupportedOperationException e) {
                              e.printStackTrace();
                        }
                  }
ASKER CERTIFIED SOLUTION
Avatar of mccarl
mccarl
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks.
You're welcome!