iChinJO
iChinJO

Reputation: 3

How to rename all files in a folder by excluding unwanted text?

I'm a beginner in Java. I would like to remove this text "_signed_20240103121502" in the file. I found many questions about rename file, but I cannot find the solution appropriate for me.

Example files

20230626_EdcPgw_0012041844_0001131023000001_ETAX_signed_20240103121502.pdf 20230626_EdcPgw_0531072999_0001131023000003_ETAX_signed_20240103121502.pdf 20230626_EdcPgw_4322053252_0001131023000005_ETAX_signed_20240103121503.pdf 20230626_EdcPgw_ETAX-PWD_signed_20240103121521.PWD

After renaming it should be like this.

20230626_EdcPgw_0012041844_0001131023000001_ETAX.pdf 20230626_EdcPgw_0531072999_0001131023000003_ETAX.pdf 20230626_EdcPgw_4322053252_0001131023000005_ETAX.pdf
20230626_EdcPgw_ETAX-PWD.PWD

Upvotes: -3

Views: 50

Answers (1)

benez
benez

Reputation: 2011

The java.nio.file.Files utility class contains all the methods you need for this.

  1. Create a regex using the Pattern class.
  2. Navigate to the folder and iterate over the files via Files.walk(..)
  3. Filter the Path by finding a match with the pattern
  4. Create the new path by replacing the found string
  5. Use Files.move(..) to rename the old to the new path

Upvotes: 0

Related Questions